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 the context of
obj.func2 to obj?
It is expected as per the standard
An
ArrowFunctiondoes not define local bindings for arguments, super, this, or new.target. Any reference toarguments,super,this, ornew.targetwithin anArrowFunctionmust 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
thisModebe the value ofF’s[[ThisMode]]internal slot.- If
thisModeis lexical, returnNormalCompletion(undefined).
So, internally it has an additional check on whether the function is lexically scoped (an arrow function) or not.
References:
[[Call]] ( thisArgument, argumentsList)OrdinaryCallBindThis ( F, calleeContext, thisArgument )If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With