个人对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

参考文档


  1. http://mp.weixin.qq.com/s/N_U3iJGntZdw9-OoxoZF8w
  2. http://mp.weixin.qq.com/s/NHlsvXs8BBHHjCrGtCVLzg
  3. http://mp.weixin.qq.com/s/2hCw0A_wE2yHn78wwJ-FyA
  4. http://mp.weixin.qq.com/s/h6acZfaF4dMZUYv8w-2oPg
  5. http://mp.weixin.qq.com/s/aBdCHKkNpjn7C5xOkDdQUQ
  6. http://mp.weixin.qq.com/s/6KubEir7Kf5t0sE8dHBbQQ
  7. http://mp.weixin.qq.com/s/BYbCgTMt7nvChPddWor0Tw
  8. http://mp.weixin.qq.com/s/39MPz6u8G9bPFBXCrg3XYw
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值