谁调用,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();//undefinedthis为new出来的对象
function People(){ this.name="limingle"; this.say=function(){ console.log(this.name); } } new People().say();//limingle通过call、apply、bind可以更改上下文
var obj={ name:"limingle", showName:function(){ console.log(this.name) } } var obj1={ name:"liulu" } obj.showName.call(obj1);//liulu箭头函数中使用的 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