问题
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
?
回答1:
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 )
来源:https://stackoverflow.com/questions/38557902/function-prototype-call-does-not-set-this-at-arrow-function