个人对this总结

    xiaoxiao2021-03-25  123

    直接调用this为window由于误操作导致this为window方法调用上下文实例化函数内的上下文通过callapplybind更改上下文箭头函数中的this参考文档

    直接调用this为window

    function showThis(){ console.log(this); } showThis();//window对象

    由于误操作导致this为window

    var obj={ name:"limingle", showName:function(){ console.log(this.name); } } var globalShowName=obj.showName; globalShowName();//undefined

    方法调用上下文

    谁调用,this就是谁

    var obj={ name:"limingle", showName1:function(){ console.log(this.name); } } obj.showName2=function(){ console.log(this.name); } function showName3(){ console.log(this.name); } obj.showName3=showName3; obj.showName4=(function(){ console.log(this.name); }).bind({}) obj.showName1();//limingle obj.showName2();//limingle obj.showName3();//limingle obj.showName4();//undefined

    实例化函数内的上下文

    this为new出来的对象

    function People(){ this.name="limingle"; this.say=function(){ console.log(this.name); } } new People().say();//limingle

    通过call、apply、bind更改上下文

    通过call、apply、bind可以更改上下文

    var obj={ name:"limingle", showName:function(){ console.log(this.name) } } var obj1={ name:"liulu" } obj.showName.call(obj1);//liulu

    箭头函数中的this

    箭头函数中使用的 this,是直接包含它的那个函数或函数表达式中的 this。

    const obj={ test(){ const arrow=()=>{ //这里的this是test()中的this //由test()的调用方式决定 console.log(this===obj); } arrow(); }, getArrow(){ return()=>{ //这里的this是getArrow()中的this //由getArrow()的调用方式决定 console.log(this===obj); } } } obj.test();//true const arrow=obj.getArrow() arrow();//true

    参考文档


    http://mp.weixin.qq.com/s/N_U3iJGntZdw9-OoxoZF8whttp://mp.weixin.qq.com/s/NHlsvXs8BBHHjCrGtCVLzghttp://mp.weixin.qq.com/s/2hCw0A_wE2yHn78wwJ-FyAhttp://mp.weixin.qq.com/s/h6acZfaF4dMZUYv8w-2oPghttp://mp.weixin.qq.com/s/aBdCHKkNpjn7C5xOkDdQUQhttp://mp.weixin.qq.com/s/6KubEir7Kf5t0sE8dHBbQQhttp://mp.weixin.qq.com/s/BYbCgTMt7nvChPddWor0Twhttp://mp.weixin.qq.com/s/39MPz6u8G9bPFBXCrg3XYw
    转载请注明原文地址: https://ju.6miu.com/read-7521.html

    最新回复(0)