- 箭头函数与父级共享this
let person = {
name: 'lucy',
say: function() {
setTimeout(function() {
console.log('name:' + this.name);
},500);
},
listen: function() {
let that = this;
setTimeout(function() {
console.log('name:' + that.name);
},1000);
},
walk: function() { this ——> person
setTimeout(() => {//与父级(walk())共享this,故 this ——> person
console.log('name:' + this.name);
},1500);
},
run: () => { //与父级共享this,父级(person) this指向的window, 此时这里的this指向window。
setTimeout(() => { //同理与父级共享this,父级(run())his指向window.
console.log('name:' + this.name);
},2000);
}
}
person.say(); //undefined
person.listen(); //lucy
person.walk(); //lucy
person.run(); //undefined
注: 箭头函数中的this指向箭头函数定义时的作用域,而不是箭头函数调用时的作用域。