Function Execution Context
It is safe to say that the keyword this
is one of the most confusing JavaScript concepts to get started with. Newbies often use this
at random until the script starts working.
A context in JavaScript is like a context in a sentence:
Petya
is running fast becausePetya
is trying to catch the train.Petya
is running fast becausehe
is trying to catch the train.
The second sentence sounds better. The sentence subject is Petya, so we can say that the sentence context is Petya because he is the focus of attention at this particular time in the sentence. Even the pronoun "who" points to Petya.
In the same way, an object can be the current execution context of a function.
// Petya is running fast because Petya is trying to catch the train.
const petya = {
username: "Petya",
showName() {
console.log(petya.username);
},
};
petya.showName();
Accessing object properties inside methods using the object name is similar to substituting Petya
with he
.
The reserved keyword this
can be used inside functions. During the execution of a function, a reference to the context object of its call is written to this
. Therefore, in the function body, you can access the properties and methods of this object.
// Petya is running fast because he (this) is trying to catch the train.
const petya = {
username: "Petya",
showName() {
console.log(this.username);
},
};
petya.showName();
Let's look at an example with a collection of books.
const bookShelf = {
authors: ["Bernard Cornwell", "Robert Sheckley”],
getAuthors() {
return this.authors;
},
addAuthor(authorName) {
this.authors.push(authorName);
},
};
console.log(bookShelf.getAuthors()); // ["Bernard Cornwell", "Robert Sheckley"]
bookShelf.addAuthor("Tanith Lee");
console.log(bookShelf.getAuthors()); // ["Bernard Cornwell", "Robert Sheckley", "Tanith Lee"]
The getAuthors
and addAuthor
methods are functions (object methods) that are called in the context of the bookShelf
object. During their execution, a reference to the bookShelf
object is written to this
, and you can refer to its properties and methods.