javascriptfunctionconstructorthisnew-operator

Why does referencing a this.function() in JavaScript not refer to the prototype element?


the below outputs true, meaning that new memory is not allocated for different objects, but they point to the same prototype Noob.

   function Noob(name, game) {
      this.name = name;
      this.game = game;
    }
    
    Noob.prototype.jersey = function () {
      console.log(this.game);
    };
    
    let p1 = new Noob("adam", "volleyball");
    let p2 = new Noob("eve", "cricket");
    
    p1.jersey();
    p2.jersey();
    
    console.log(p1.jersey === p2.jersey);

This one outputs false, meaning new memory is created for different objects. If I were to remove this keyword from the jersey function, then it returns true.

function Noob(name, game) {
  this.name = name;
  this.game = game;
  this.jersey = function () {
    console.log(this.game);
  };
}

let p1 = new Noob("adam", "volleyball");
let p2 = new Noob("eve", "cricket");

console.log(p1.jersey === p2.jersey);

I am confused whether this is related to the lexical scope of the this keyword or something with the new keyword.


Solution

  • The short answer is no. As you wrote, it depends if it belongs to the prototype, and therefore all the instances point to the same function, or if a new function object is assigned each time an object is created, which means that each instance points to a unique function object.

    The ‘new’ keyword or the lexical scope are not related. If you did for example:

    for (obj in objects) {
      obj.foo = function(){};
    }
    

    You’d also see that objects[0].foo === objects[1].foo returns false.