this in Method Calls

Share this video with your friends

Send Tweet

When a function is called as a method of an object, that function's this argument is set to the object the method is called on. That object is called the receiver of the function call.

Oftentimes, the receiver gets lost when we invoke a method as a function. This happens particularly often when passing a method as a callback to another function.

In this lesson we'll see how the receiver mechanism works, what problems it creates, and how to work around these problems using wrapper functions or the bind method.

David Chan
David Chan
~ 7 years ago

There are many typos in this code snippet.

Marius Schulz
Marius Schulz(instructor)
~ 7 years ago

There are many typos in this code snippet.

Could you please point out the typos? I can’t seem to find a single one. 🤔

David Chan
David Chan
~ 7 years ago

There are many typos in this code snippet.

Could you please point out the typos? I can’t seem to find a single one. 🤔

Sorry, I might not point it out clearly, it's actually the code snippet in the Transcript part.

Typos are like

const person = {
    console.log(`Hi, my name is ${this.firstName}!`);
};

sayHi() {
    firstName: "John",
}

and

const greet = person.sayHi();
greet();
Pesto
Pesto
~ 6 years ago

why does wrapping the call to sayHi inside setTimeout() with a function

fn(){
person.sayHi();
} 

didn't set 'this' to global? I get why it is happening without the fn() but not this part.

Marius Schulz
Marius Schulz(instructor)
~ 6 years ago

@Pesto: Within the wrapper function, person.sayHi() invokes the sayHi with person as a receiver. sayHi is invoked as a method, and it doesn't matter what value this has within the surrounding scope.

Lars Devocht
Lars Devocht
~ 5 years ago

@Maris: Especially useful are your hints to solve the issue of losing the receiver of a method call. Some teachers present it as a language error and then solve it with a fallback to lexical scoping with self=this. The best explanation about "this" I found so far. Thank you.