Function.prototype.call不会在Arrow Function处设置它 [英] Function.prototype.call does not set this at Arrow Function

查看:76
本文介绍了Function.prototype.call不会在Arrow Function处设置它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意,相关此内部对象方法的值?



给定

  var obj = {
property :5,
func1:function(){
console.log(this.property);
},
func2 :()=> {
console.log(this.property);
}
}

this Window at obj.func2()



尝试使用函数.prototype.call()将设置为 obj 仍为窗口



< pre class =snippet-code-js lang-js prettyprint-override> var obj = {property:5,func1:function(){console.log(this.property); },func2:()=> {console.log(this.property); obj.func2.call(obj);


  1. 这是预期的行为吗?


  2. 为什么 Function.prototype.call()未设置上下文
    obj.func2 obj



解决方案

预计按标准


ArrowFunction 没有为arguments,super,this或new.target定义本地绑定。对参数的任何引用 super 或< 中的code> new.target ArrowFunction 必须解析为词汇封闭环境中的绑定。


这意味着 - 您无法设置未定义的内容。



此外,相关:



使用 [[Call]] 设置绑定为



  1. 执行 OrdinaryCallBindThis(F,calleeContext ,thisArgument)


其中支票



  1. thisMode 成为值 F [[ThisMode]] 内部广告位。

  2. 如果 thisMode 是词法,则返回 NormalCompletion(未定义)


因此,在内部它还会检查函数是否是词法范围(箭头函数)。



参考文献:




Note, Related Value of this inside object method?

Given

var obj = {
  property: 5,
  func1: function () {
    console.log(this.property);
  },
  func2: () => {
    console.log(this.property);
  }
}

this would be Window at obj.func2().

When tried setting this to obj using Function.prototype.call(), this was still Window

var obj = {
  property: 5,
  func1: function () {
    console.log(this.property);
  },
  func2: () => {
    console.log(this.property);
  }
}

obj.func2.call(obj);

  1. Is this expected behaviour?

  2. Why does Function.prototype.call() not set the context of obj.func2 to obj?

解决方案

It is expected as per the standard

An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment.

That means - you cannot set something that is not defined.

Also, relevant:

The functions are called with the [[Call]] internal slot that sets the this binding as

  1. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).

Which in turn checks

  1. Let thisMode be the value of F’s [[ThisMode]] internal slot.
  2. If thisMode is lexical, return NormalCompletion(undefined).

So, internally it has an additional check on whether the function is lexically scoped (an arrow function) or not.

References:

这篇关于Function.prototype.call不会在Arrow Function处设置它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆