this的指向问题

this:指向一个对象,根据不一样状况,指向也不一样

1.默认this指向window(这个全局变量):经过this.object能够访问全局的数据
2.在严格模式下 'use strict' 函数内function(){console.log(this)} 中this未undefined;app

var people ={
name:'xmj',
console:()=>{console.log(this)},//this =window
show:function(){函数

console.log(this)

}
}
// people.console();
// people.show();//this=people;this

/当this为对象内的方法,而且是通常的function()/
var people ={
name:'xmj',
show:function(){code

console.log(this)//this指向这个实例化的对象people,this.name ='xmj';

}
}对象

//this:找到最近的实例化对象
var num =1;
function Num(){
var num =2;
return this.num;//this=window,由于Num只是一个模板不是实例化,this.num=1;
}继承

//将this指向内部:定义一个实例让其指向这个实例 eg:
var Num1={io

num:2,

Num:function(){ console.log(this.num)}//this =Num1 ,已经实例化的Num1
}
/function 和()=>中this的指向**/
var num2 =1;
var Num2={console

num2:2,
 //用普通函数function定义时指向这个对象Num2
 //Num2:funtion(){console.log(this)}//this =Num2

 //当用箭头函数()=>定义指向上下文最近的对象的父this,只能经过继承其余的this,最近并无this eg:
 Num1:()=>{
        console.log(this);//this =window,上下文中只有Num2这个绑定了对象,这个对象Num2的父this为window
 }

}
Num2.Num1(); function

/对于有明确指向function的this能够经过apply call bind来更改this的指向/模板

var obj={ a:'1', b:'2',};function Add(index){ console.log(this.a);// this指向实例化对象 obj; this.a ='1'; this.a =index; console.log(this.a) //更改this.a的值,this.a='3'}Add.apply(obj,['3']);//其中apply的参数是[data1,data2,data3],而call参数是call(obj,data1,data2,....)

相关文章
相关标签/搜索