关于前端:this的指向问题

2次阅读

共计 1186 个字符,预计需要花费 3 分钟才能阅读完成。

  this: 指向一个对象,依据不同状况,指向也不同 

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

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

     console.log(this)

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

/ 当 this 为对象内的办法, 并且是个别的 function()/
var people ={
name:’xmj’,
show:function(){

     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={

num:2,

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

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 的 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,….)

正文完
 0