obj = {
name:'lili',
age:20,
sayAge1:function(){
// obj调用sayAge1(),则this指向obj,this.name相当于obj.name
console.log('my name is ' + this.name + ' my age is ' + this.age)
},
sayAge2:() =>{
// 箭头函数的this指向最近的函数的this,而sayAge2()外层没有函数,所以this指向的是window
console.log('my name is ' + this.name + ' my age is ' + this.age)
},
// obj调用sayAge3,那么sayAge3函数的this指向obj,箭头函数的this指向sayAge3中的this,也就指向了obj
sayAge3:function(){
setTimeout(()=>{
console.log('my name is ' + this.name + ' my age is ' + this.age)
},2000)
},
//setTimeout并没有直接调用者,所以function中的this指向window
sayAge4:function(){
setTimeout(function(){
console.log('my name is ' + this.name + ' my age is ' + this.age)
},1000)
}
}
obj.sayAge1()
obj.sayAge2()
obj.sayAge3()
obj.sayAge4()
应用场景:
1、例如定义了一个obj对象,对象里面定义了属性是函数,而函数属性里面又执行了setTimeout函数,需要打印对象中的一些属性值,这个时候可以用箭头函数,因为obj调用函数属性,那么函数属性的this指向obj,而函数属性里面的箭头函数的this指向函数属性的this,就指向了obj
2、在构造函数中,需要在函数内建一个定时器,打印函数内部的this.name,那么使用需要使用箭头函数
var env = 'outside'
function Test() {
this.env = 'inside';
setTimeout(()=>{
console.log("函数内部env~"+this.env)
},1000)
setTimeout(function(){
console.log("函数外部env~"+this.env)
},2000)
}
const test = new Test();
改变this指向的方法:
- apply
- call
- bind
- 构造函数实例化new时,this指向新创建的这个实例
- 构造函数return{对象}时,this指向return的这个对象