Create an object user with a property name and a method sayName that logs the name using this. Then, call the sayName function.
this in JavaScriptThe value of this depends on how a function is called, and it can be tricky to understand.
In the global scope, this refers to the global object (window in browsers).
console.log(this); // window (in browsers)When a function is called as a method of an object, this refers to that object.
const obj = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
obj.greet(); // Alice
In strict mode, this is undefined inside a function not called as an object method.
function show() {
console.log(this);
}
show(); // undefined (in strict mode)
Arrow functions do not have their own this. They inherit this from the surrounding (lexical) scope.
const obj = {
name: 'Bob',
greet: () => {
console.log(this.name);
}
};
obj.greet(); // undefined (because `this` is from outside)