this keyword Questions Javascript
Q1. What is the output?
const user = {
firstName: "Chaitanya",
getName() {
const firstName = "Shahare";
return this.firstName;
},
};
console.log(user.getName());
?
// Chaitanya
Q2. What is the result of accessing its ref? why?
function makeUser() {
return {
name: "John",
ref: this,
};
}
let user = makeUser();
console.log(user.ref.name);
?
// no output
- this refers to the window / global object and not the object that is being returned
Followup: how to use ref.name
function makeUser() {
return {
name: "John",
ref() {
return this;
},
};
}
let user = makeUser();
?
console.log(user.ref().name); // John
Q3. What is the output?
const user = {
name: "Chaitanya Shahare",
logMessage() {
console.log(this.name); // What is logged?
}
}
setTimeout(user.logMessage, 1000);
?
// undefined
user.logMessageis used as a callbackthiswill refer to the global or window object
Followup: how do we fix it? make it log name
const user = {
name: "Chaitanya Shahare",
logMessage() {
console.log(this.name); // What is logged?
}
}
setTimeout(user.logMessage, 1000);
?
const user = {
name: "Chaitanya Shahare",
logMessage() {
console.log(this.name); // What is logged?
}
}
setTimeout(function() {
user.logMessage();
}, 1000); // Chaitanya Shahare
Q4. What is the output?
const user = {
name: "Chaitnaya",
greet() {
return `Hello, ${this.name}!`;
},
farewell: () => {
return `Goodbye, ${this.name}!`;
},
};
console.log(user.greet());
console.log(user.farewell());
?
console.log(user.greet()); // Hello, Chaitanya
console.log(user.farewell()); // Goodbye, undefined
- As arrow function has this variable pointing to the parent's this
Q5. Create an object calculator
let calculator = {
// ... your code ...
}
calculator.read(); // read 2 values from the user
console.log(calculator.sum()); // add the 2 values
console.log(calculator.mul()); // multiply the 2 values
?
Answer
let calculator = {
read() {
this.a = +prompt("a = ", 0);
this.b = +prompt("b = ", 0);
},
sum() {
return this.a + this.b;
},
mul() {
return this.a * this.b;
}
}
calculator.read();
console.log(calculator.sum());
console.log(calculator.mul());
Q6. What will be the output?
var length = 4;
function callback() {
console.log(this.length); // What is logged?
}
const object = {
length: 5,
method(fn) {
fn();
},
};
object.method(callback); // What is logged?
Answer
- 4
Followup: What is logged?
var length = 4;
function callback() {
console.log(this.length); // What is logged?
}
const object = {
length: 5,
method(fn) { // arguments = [callback, 2, 3]
arguments[0]();
},
};
object.method(callback, 2, 3); // What is logged?
?
Answer
- 3
Q7. Implement calc
const result = calc.add(10).multiply(5).substract(30).add(10);
console.log(result.total);
?
Answer
const calc = {
total: 0,
add(a) {
this.total += a;
return this;
},
multiply(a) {
this.total *= a;
return this;
},
substract(a) {
this.total -= a;
return this;
},
}
const result = calc.add(10).multiply(5).substract(30).add(10);
console.log(result.total);