JavaScript this Keyword
this is a special keyword that points to an object. Which object depends on how the function is called, and not on where it is written (except for arrow functions).
| Where | What this is |
|---|---|
| In an object method | The object before the dot |
| In a normal function (strict mode) | undefined |
| In a normal function (not strict, browser) | The window object |
| In an arrow function | The this of the outer code |
In a constructor with new | The new object |
| In an event handler | The element that got the event |
this in a method
const user = {
name: "Robin",
show() {
console.log(this.name);
}
};
user.show();
Output of the above program is
Robin
Losing this
If you copy the method into a variable and call it alone, this is not user any more.
const show = user.show;
show(); // this is undefined or window, so this.name is not "Robin"
Fix with bind, call and apply
function hello(greeting) {
console.log(greeting + ", " + this.name);
}
const person = { name: "Maria" };
hello.call(person, "Hi"); // call now
hello.apply(person, ["Hello"]); // arguments as an array
const bound = hello.bind(person); // make a new function
bound("Hey");
Output of the above program is
Hi, Maria
Hello, Maria
Hey, Maria
Arrow functions
An arrow function takes this from the code around it. This is useful inside a method, for a callback.
const timer = {
name: "Clock",
start() {
[1, 2].forEach(n => {
console.log(this.name + " " + n); // this is still timer
});
}
};
timer.start();
Output of the above program is
Clock 1
Clock 2
Note:
Do not write an object method as an arrow function. show: () => this.name will not point to the object.
Summary
thisdepends on how a function is called.- Use
call,applyorbindto set it by hand. - Arrow functions keep the outer
this. - Next: JavaScript Classes.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |