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 callsrunwiththis === obj. - Explicit binding:
fn.call(obj)andfn.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 asthisunless construction semantics return another object. - Plain call: in strict mode,
fn()receivesundefinedasthis. 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.