this
?A keyword that points to the element it's inside of. If you were to think about it in English, this
is like when you say my, or mine.
this
bindings:When in the global scope, the value of this
will be the window/console Object;
Example:
function sayName(name) {
console.log(this); // referring to window/console
return name;
}
sayName("D'Artagnan");
Whenever a function is called by a preceding dot, the object before that dot is this
.
Example:
const myObj = {
greeting: 'Hello',
sayHello: function(name) {
console.log(`${this.greeting} my name is ${name}`);
console.log(this);
}
};
myObj.sayHello('Ryan');
Example 2:
const sayNameFunc = obj => {
obj.sayName = function() {
console.log(`Hello my name is ${this.name}`);
console.log(this);
};
};
const me = { name: 'Ryan' };
const you = { name: 'Freddy' };
sayNameFunc(me);
sayNameFunc(you);
// Invoke Methods on our objects
me.sayName();
you.sayName();