Skip to main content

interview question on this

Q1:

const person = {
name: "Alice",
greet: function () {
console.log(this.name);
},
};

const greet = person.greet;
person.greet(); // ?
greet(); // ?

Q2:

function showThis() {
console.log(this);
}

const obj = {
method: showThis,
};

showThis(); // ?
obj.method(); // ?

Q3:

const car = {
brand: "Toyota",
getBrand: function () {
const innerFunc = () => {
console.log(this.brand);
};
innerFunc();
},
};

car.getBrand(); // ?

Q4:

const obj = {
value: 100,
showValue: function () {
console.log(this.value);

function innerFunc() {
console.log(this.value);
}

innerFunc();
},
};

obj.showValue(); // ?

Q5:

class Person {
constructor(name) {
this.name = name;
}

greet() {
console.log(this.name);
}
}

const person = new Person("John");
const greet = person.greet;
person.greet(); // ?
greet(); // ?

Q6:

const team = {
members: ["Alice", "Bob"],
showMembers: function () {
this.members.forEach(function (member) {
console.log(this);
});
},
};

team.showMembers(); // ?