In the following code, the "this" keyword references the "myName" object. Why doesn’t the "this" in console.log reference the "window" object, since it is really "window.console.log"?
class Name {
constructor(firstName) {
this.firstName = firstName;
}
superGreet() {
console.log('I am', this.firstName);
}
}
let myName = new Name("Jay");
myName.superGreet();
3
Answers
Arguments are evaluated in the caller’s scope, not the scope of the function being called. So
is equivalent to
In this rewrite you can see that
this
is in the scope ofmyName.superGreet()
, notwindow.console.log()
. Sothis
is the value ofmyName
.When
console.log('I am', this.firstName);
is run, the arguments are evaluated first before callingconsole.log
. Thereforethis.firstName
is evaluated in the context of the Name object, and thethis
refers to the Name object.You defined a class called ‘Name’ but instantiated it with ‘Cat’. Assuming you meant to use the correct class name.