javascriptscopeprototypejavascript-scope

changing value in prototype does not work in JavaScript


I am new in JS, lets have a look on my code bellow.

I want to change value of legs property of mouse to 2 while using proto but I am unable to change it. All I am getting in output is 4. Please help why is this ?

function Animal() {
  this.legs = 4;
}

var mouse = new Animal();

mouse.__proto__.legs = 2;
console.log(mouse.legs);


Solution

  • As commented, the leg you are trying to access is a self owned property and not on prototype.

    Following is a sample:

    function Animal() {
      this.legs = 4;
    }
    Animal.prototype.legs = 8;
    var mouse = new Animal();
    
    mouse.legs = 2;
    console.log(mouse.legs, mouse.__proto__.legs);


    That said, if you wish to have a override concept implementation, always remember, never mutate/change property on prototype.

    Idea is to have common property on prototype and have custom property on self.

    Following is a sample depicting the same:

    function Animal() { this.legs = 4; }
    function Reptile() { this.legs = 4; }
    
    Reptile.prototype = new Animal();
    var mouse = new Reptile();
    console.log('Mouse details : ', mouse.legs, mouse.__proto__.legs);
    
    var snake = new Reptile();
    snake.leg = 0;
    console.log('Snake details : ', snake.legs, snake.__proto__.legs);
    
    snake.__proto__.legs = 0;
    
    console.log('After mutation')
    
    console.log('Mouse details : ', mouse.legs, mouse.__proto__.legs);
    console.log('Snake details : ', snake.legs, snake.__proto__.legs);


    To simply put, everything in JS is an object. When you create an object, it has 2 nested levels by default:

    -> this
    -> __proto__

    Any property of your constructor goes to this. Any property on its prototype goes to __proto__. Since all objects are inherited from Object, there is a chain till global object.