Function.prototype.call不会在Arrow Function处设置它 [英] Function.prototype.call does not set this at 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
此
仍为窗口
var obj = {property:5,func1:function(){console.log(this.property); },func2:()=> {console.log(this.property); obj.func2.call(obj);
-
这是预期的行为吗?
-
为什么
Function.prototype.call()
未设置上下文
obj.func2
到obj
?
预计按标准
ArrowFunction
没有为arguments,super,this或new.target定义本地绑定。对参数的任何引用
,super
,此
或<中的code> new.target ArrowFunction 必须解析为词汇封闭环境中的绑定。
这意味着 - 您无法设置未定义的内容。
此外,相关:
使用 [[Call]]
设置此$ c $的内部插槽c>绑定为
- 执行
OrdinaryCallBindThis(F,calleeContext ,thisArgument)
。
其中支票
- 让
thisMode
成为值F
的[[ThisMode]]
内部广告位。
- 如果
thisMode
是词法,则返回NormalCompletion(未定义)
。
因此,在内部它还会检查函数是否是词法范围(箭头函数)。
参考文献:
- 14.2.16运行时语义:评估
- 9.2.1
[[Call]](thisArgument,argumentsList)
- 9.2.1.2
OrdinaryCallBindThis(F,calleeContext,thisArgument)
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);
Is this expected behaviour?
Why does
Function.prototype.call()
not set thecontext
ofobj.func2
toobj
?
It is expected as per the standard
An
ArrowFunction
does not define local bindings for arguments, super, this, or new.target. Any reference toarguments
,super
,this
, ornew.target
within anArrowFunction
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
- Perform
OrdinaryCallBindThis(F, calleeContext, thisArgument)
.
Which in turn checks
- Let
thisMode
be the value ofF
’s[[ThisMode]]
internal slot.- If
thisMode
is lexical, returnNormalCompletion(undefined)
.
So, internally it has an additional check on whether the function is lexically scoped (an arrow function) or not.
References:
- 14.2.16 Runtime Semantics: Evaluation
- 9.2.1
[[Call]] ( thisArgument, argumentsList)
- 9.2.1.2
OrdinaryCallBindThis ( F, calleeContext, thisArgument )
这篇关于Function.prototype.call不会在Arrow Function处设置它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!