箭头函数中this指向父作用域
实例一
1.
let a = {
foo: 1,
bar: () => console.log(this.foo)
}
a.bar() //undefined
bar函数中的this指向父作用域,而a对象没有作用域,因此this不是a,打印结果为undefined
function A() {
this.foo = 1
}
A.prototype.bar = () => console.log(this.foo)
let a = new A()
a.bar() //undefined
原型上使用箭头函数,this指向是其父作用域,并不是对象a,因此得不到预期结果
实例二
obj1 = {
birth: 1990,
getAge: () => { console.log(this) } // this指向window对象
}
obj1.getAge()
// 输出Window 对象
实例三
obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = () => {new Date().getFullYear() - this.birth; console.log(this)}; // this指向obj对象
return fn(); //返回fn
}
};
obj.getAge(); // 29
// 输出一个对象
// {birth: 1990, getAge: ƒ()}
实例四
1.function
var obj = {
birth: 1990,
getAge: function(){
console.log(new Date().getFullYear() - this.birth); //this指向obj对象
}
}
obj.getAge() // 29
var obj = {
birth: 1990,
getAge: function () {
var b = this.birth // 1990
var fn = function () {
return new Date().getFullYear() - this.birth; // this指向window或undefined
}
return fn()
}
}
obj.getAge() // NaN
2.箭头函数
var obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
return fn()
}
}
obj.getAge(); // 29
var obj = {
getAge: () => {
console.log(this); // window
}
}
obj.getAge(); //window
作为对象的属性时,this的指向则不再是对象本身了,箭头函数捕获的是obj{}这个对象的环境,然后这个环境的this指向的是window