JavaScript · Middle · Question 1 of 75
What does this code print?
const user = {
name: "Ann",
greet() { return this.name; },
};
const greet = user.greet;
console.log(greet());- ✓Correct answer:
undefined(or an error in strict mode): the context is lost - 2
"Ann": a method remembers the object it was declared in - 3
"greet":thispoints to the function itself
Explanation
this is determined by how a function is called, not where it's declared. greet() is called without an object before the dot, so this is undefined in strict mode (the global object in sloppy mode). Fix it with user.greet.bind(user) or by calling user.greet().