JavaScript this and Ordinary Function Receivers
Quick answer
For ordinary functions, this depends on how a function is invoked. A method call normally supplies the object before the property access as its receiver.
How it works
In obj.method(), the property reference carries obj into the call. Assigning the function to a variable and calling that variable does not preserve obj. For a strict ordinary function called without a receiver, this is undefined. Sloppy calls can substitute the global object and box primitives; do not depend on that behavior.
function read() { return this.price; }const a = {price: 4, read}; const b = {price: 9, read};console.log(a.read(), b.read());Expected output in Node.js:
4 9The same function receives different objects at the two call sites.
const item = {check() { "use strict"; return this === undefined; }};const detached = item.check; console.log(item.check(), detached());Expected output in Node.js:
false trueThe detached strict call has no object receiver.
Common mistakes
A method is not permanently attached to the first object that stores it.
Practice
Explain why assigning a method to a variable changes the second example.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript this and Ordinary Function Receivers — Knowledge Check
Apply the taught concept and predict the output.
What supplies this in obj.method() for an ordinary method?
What does extracting an ordinary method into a variable preserve?
What is this in a strict plain function call?
What is the exact console output in JavaScript this and Ordinary Function Receivers example 1?
function read() { return this.price; }const a = {price: 4, read}; const b = {price: 9, read};console.log(a.read(), b.read());What is the exact console output in JavaScript this and Ordinary Function Receivers example 2?
const item = {check() { "use strict"; return this === undefined; }};const detached = item.check; console.log(item.check(), detached());