This Keyword - Objects Flashcards

1
Q

What is the value of this and why?

let myObj = {
name: ‘Kumar’,
getName: function () {console.log(this.name)}
}

myObj.getName();

A

Kumar

  1. When defining an object ‘this’ is defined as the object.
  2. When the function is invoked is part of the
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the value of this and why?

let myObj = {
name: ‘Kumar’,
getName: () => {console.log(this)}
}

myObj.getName();

A

Window

  1. This is an object expression
  2. Arrow function don’t have their own this.
  3. Arrow function take their ‘this’ from the previous exectuion context which in this situation is the window/global object.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the value of this.firstName and why?

let user = {
firstName: “John”,
sayHi() {
alert(Hello, ${this.firstName}!);
}
};

setTimeout(user.sayHi, 1000);

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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);

A

John

This works, because it receives user from the outer lexical environment ie closure, and then calls the method normally.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly