This Keyword - Objects Flashcards
What is the value of this and why?
let myObj = {
name: ‘Kumar’,
getName: function () {console.log(this.name)}
}
myObj.getName();
Kumar
- When defining an object ‘this’ is defined as the object.
- When the function is invoked is part of the
What is the value of this and why?
let myObj = {
name: ‘Kumar’,
getName: () => {console.log(this)}
}
myObj.getName();
Window
- This is an object expression
- Arrow function don’t have their own this.
- Arrow function take their ‘this’ from the previous exectuion context which in this situation is the window/global object.
What is the value of this.firstName and why?
let user = {
firstName: “John”,
sayHi() {
alert(Hello, ${this.firstName}!
);
}
};
setTimeout(user.sayHi, 1000);
Undefined.
Once a method is passed somewhere separately from the object – this is lost.
That’s because setTimeout got the function user.sayHi, separately from the object. The last line can be rewritten as:
let f = user.sayHi;
setTimeout(f, 1000); // lost user context
What is the value of this.firstName and why?
let user = {
firstName: “John”,
sayHi() {
alert(Hello, ${this.firstName}!
);
}
};
setTimeout(function() {
user.sayHi(); // Hello, John!
}, 1000);
John
This works, because it receives user from the outer lexical environment ie closure, and then calls the method normally.