关于this指向
this是js中一个难点,通常来讲,this就是指向当前的运行环境,js对象可以看成全局对象和局部对象,当函数直接在全局环境中运行,则this指向全局对象
function foo()
{
console.log(this);
}
foo();//输出window
第二种,当this在对象中的时候,this 指向的是该对象
var obj ={
name :"Jack",
value :"can play pubg",
play : function(){
console.log(this.name + this.value)
}
};
obj.play(); //输出Jack can play pubg
第三种,当this在构造函数中的时候,this 将会指向新的实例,此时this 会通过new 关键字指向实例,详细的下回开专题讲
function Foo(name,value){
this.name = name;
this.value = value;
this.play = function(){
console.log(this.name + this.value);
}
}
var foo = new Foo("peter","can do it");
foo.play();//输出 Peter can do it
第四种,当this被apply 和 call 以及bind 函数使用时 会改变当前的运行环境
let a =5; let b =3; let sub =(a,b) => a - b; let add =(a,b) => a + b; console.log(sub.call(add,a,b)); // 改变add的运行环境 输出为2
this关键字在写插件时尤其重要,一定要反复理解

浙公网安备 33010602011771号