Check this【BFE.dev】

The 19th on BFE.dev, here is the link this.

const obj = {
  a: 1,
  b: function() {
    console.log(this.a)
  },
  c() {
    console.log(this.a)
  },
  d: () => {
    console.log(this.a)
  },
  e: (function() {
    return () => {
      console.log(this.a);
    }
  })(),
  f: function() {
    return () => {
      console.log(this.a);
    }
  }
}

The code above initialize an obj, and there is a series of output that we need to figure out.

console.log(obj.a)
obj.b()
;(obj.b)()
const b = obj.b
b()
obj.b.apply({a: 2})
obj.c()
obj.d()
;(obj.d)()
obj.d.apply({a:2})
obj.e()
;(obj.e)()
obj.e.call({a:2})
obj.f()()
;(obj.f())()
obj.f().call({a:2})

The first one is console.log(obj.a) and this is 1 obviously, because this is point to obj itself here.

For obj.b(), the pointer of this is also obj, so the result is also 1.

(obj.b)() is same as obj.b(), so the result is also 1.

Then here we have a const b which equals to obj.b and after that we call this b, so the reference of this here is window object, and window object doesn’t have a property, so the output is undefined.

Next, here we call an apply function to obj.b and there is a object {a: 2}, so the this reference at this time is point to the object {a: 2}, so the output is 2.

Obj.c() is same as obj.b(), so it is 1 here.

Obj.d(), because d is an arrow function, it has no this itself, so it can’t find a, and return undefined.

(obj.d)() is same as obj.d(), so the result is also undefined.

Next we have an apply function to obj.d, but d is an arrow function, apply function is invalid for it, so it is undefined.

Obj.e(), e property is an immediate execution function, but it returns an arrow function here, so it also have no this reference itself, return undefined absolutely.

And next one is (obj.e)(), if you saw above, you know that it is same between obj.e() and (obj.e)(), so it return undefined.

Also here we called call function to obj.e, but the arrow function inside means it can’t be useful, so return undefined.

Next one is obj.f()(), so the f property here is a function which returns an arrow function and we can see there is a closure here, so the inside function called outside level context, and used a property outside, so it returns 1.

Followed by it is (obj.f())(), so it is same as obj.f()(), so it also returns 1.

Last one is obj.f().call({a: 2}), here we can see the f property returned an arrow function, so the call function here is invaild, so it will return 1 like above.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值