skip to Main Content

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


  1. Arguments are evaluated in the caller’s scope, not the scope of the function being called. So

      superGreet() {
        console.log('I am', this.firstName);
      }
    

    is equivalent to

      superGreet() {
        let temp = this.firstName;
        console.log('I am', temp);
      }
    

    In this rewrite you can see that this is in the scope of myName.superGreet(), not window.console.log(). So this is the value of myName.

    Login or Signup to reply.
  2. When console.log('I am', this.firstName); is run, the arguments are evaluated first before calling console.log. Therefore this.firstName is evaluated in the context of the Name object, and the this refers to the Name object.

    Login or Signup to reply.
  3. You defined a class called ‘Name’ but instantiated it with ‘Cat’. Assuming you meant to use the correct class name.

    class Name {
      constructor(firstName) {
        this.firstName = firstName;
      }
      superGreet() {
        console.log('I am', this.firstName);
      }
    }
     
    let myName = new Name("Jay");
    myName.superGreet();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search