箭头函数中的this指向

箭头函数中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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值