Book
Submodule 12.2: JavaScript Objects
Submodule 12.2: JavaScript Objects
Completion requirements
View
- Objects Introduction
- Access Object Properties
- Changing, Adding and Deleting properties
- Object Methods
- The this keyword
The this keyword
In the previous chapter, we saw the this keyword to be used inside an object. But what is this?
In general the keyword this refers to the context in which the function called is located.
In our previous example:
var darkChoco = {
cacao:"80%",
milk:"0%",
grams:100,
getFullInfo : function () {
return this.cacao + " " + this.milk + " " + this.grams;
}
};
this refers to the values of cacao, milk and grams.
The meaning of this changes, depending on where we use it.
Now, open your console and type : this;
What do you see?
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
When there is no function related to this and we call it, the environment of this is the global context. In a web browser, any javaScript code not specified, has Window as its global object. Thus, in this case, this refers to the Window object.
Another very important usage of this is in the constructor functions. We will learn more about it in the next Sub-module.