对象中 函数的this指向(箭头函数与普通函数)

let obj1 = {
a: 1,
foo: () => {
console.log(this.a)
    }
}
obj1.foo()//问题1

const obj2 = obj1.foo

obj2()//问题2

答案:两个都是undefined。

    let obj1 = {
        a: 1,
        foo: function () {
            console.log(this.a);
        }
    }

    obj1.foo()//?

    const obj2 = obj1.foo

    obj2()//?

答案:1和undefined。

  • 普通函数的this指向:

1.普通函数的this总是指向它的直接调用者。

2.在严格模式下,没找到直接调用者,则函数中的this是undefined。

3.在默认模式下(非严格模式),没找到直接调用者,则函数中的this指向window。

  • 箭头函数的this指向:

1.没有this指向,this永远来自其上下文的 this;
2.任何方法都改变不了其指向,如call(), bind(), apply();
3.箭头函数不能用作构造器,和 new一起用会抛出错误
4.箭头函数没有prototype(原型)属性
5.不绑定arguments,该对象在函数体内不存在,如果要用的话,可以用rest参数代替;
6.箭头函数和匿名函数是有区别的(this指向的不同)。

普通匿名函数与箭头函数 this 区别

 var obj1 = {
        count: 1,
        getCount: function (y) {
            console.log(this);  //{count: 1, getCount: ƒ}
            let fn = function (y) {
                console.log(this);  //Window
                return y + this.count;
            }
            return fn(y);
        }
    }

    console.log(obj1.getCount(6));//NaN 
        //getCount是普通函数,this指向调用它的对象,
        //fn是匿名函数,this指向Window。

    var obj2 = {
        count: 2,
        getCount: function (y) {
            console.log(this);   //{count: 2, getCount: ƒ}
            let fn = (y) => {
            console.log(this);  //{count: 2, getCount: ƒ}
              return  y - this.count;
            }
            return fn(y);
        }
    }

    console.log(obj2.getCount(6));//4  
          //getCount是普通函数,this指向调用它的对象,
         //fn是箭头函数,this指向包着他的函数的this。

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值