Function.prototype.call 没有在箭头函数中设置这个
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
在 obj.func2()
。
当尝试使用 Function.prototype.call()
将 this
设置为 obj
时,this
仍然是 Window
var obj = {
property: 5,
func1: function () {
console.log(this.property);
},
func2: () => {
console.log(this.property);
}
}
obj.func2.call(obj);
这是预期的行为吗?
为什么Function.prototype.call()
不设置context
obj.func2
到 obj
?
预计按照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.
这意味着 - 您不能设置未定义的内容。
另外,相关的:
使用 [[Call]]
内部插槽调用函数,将 this
绑定设置为
- Perform
OrdinaryCallBindThis(F, calleeContext, thisArgument)
.
这又是checks
- Let
thisMode
be the value of F
’s [[ThisMode]]
internal slot.
- If
thisMode
is lexical, return NormalCompletion(undefined)
.
因此,它在内部会额外检查函数是否在词法范围内(箭头函数)。
参考文献:
注意,相关
给定
var obj = {
property: 5,
func1: function () {
console.log(this.property);
},
func2: () => {
console.log(this.property);
}
}
this
将是 Window
在 obj.func2()
。
当尝试使用 Function.prototype.call()
将 this
设置为 obj
时,this
仍然是 Window
var obj = {
property: 5,
func1: function () {
console.log(this.property);
},
func2: () => {
console.log(this.property);
}
}
obj.func2.call(obj);
这是预期的行为吗?
为什么
Function.prototype.call()
不设置context
obj.func2
到obj
?
预计按照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.
这意味着 - 您不能设置未定义的内容。
另外,相关的:
使用 [[Call]]
内部插槽调用函数,将 this
绑定设置为
- Perform
OrdinaryCallBindThis(F, calleeContext, thisArgument)
.
这又是checks
- Let
thisMode
be the value ofF
’s[[ThisMode]]
internal slot.- If
thisMode
is lexical, returnNormalCompletion(undefined)
.
因此,它在内部会额外检查函数是否在词法范围内(箭头函数)。
参考文献: