Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function.prototype.call does not set this at Arrow Function [duplicate]

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?

like image 967
guest271314 Avatar asked Dec 29 '25 09:12

guest271314


1 Answers

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:

  • 14.2.16 Runtime Semantics: Evaluation
  • 9.2.1 [[Call]] ( thisArgument, argumentsList)
  • 9.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument )
like image 61
zerkms Avatar answered Dec 31 '25 00:12

zerkms