The keyword this is commonly used inside functions and objects. Where the function is declared, alters what this means. It always refers to one object, usually the object in which the function operates.
let JS = {
name: "JavaScript",
age: 24,
introduce: function() {
return `Hi, my name is ${this.name}. I'm ${this.age} years old.`;
}
};
console.log(JS.introduce());
:gem::gem::gem: It is very important to know the effect of
fat arrow functionsince the later is not writingthiskeyword which can break or giving unexpected results.
Check this example out and guess the results:
let width = 600;
let shape = { width: 300 };
let showWidth = function() {
console.log(this.width);
};
shape.getWidth = showWidth;
shape.getWidth();
What do you think about the result ???
:gem: read more about it here.