AceDevHub
Intermediate JavaScript Interview QuestionsIntermediateConcept

JavaScript · Question 35

How is the value of this determined in a regular JavaScript function?

Direct answer

For a regular function, this is primarily determined by how the function is called: as a method, with call/apply/bind, with new, or as a plain function; arrow functions are different because they capture this lexically.

A useful interview model is to inspect the call site. The same function object can receive different this values when invoked in different ways.

  • Method call: obj.run() usually calls run with this === obj.
  • Explicit binding: fn.call(obj) and fn.apply(obj) invoke immediately with the chosen receiver; fn.bind(obj) creates a bound function.
  • Constructor call: new Fn() creates a new object and calls the constructor with that object as this unless construction semantics return another object.
  • Plain call: in strict mode, fn() receives undefined as this. Non-strict scripts can substitute the global object.

The key distinction is that this is not normally decided by where a regular function was declared. That lexical rule belongs to arrow functions.