0

I have trouble to understand this, even fumble around on internet. Here is my snippet in javscript:

    TEST=function(){};
    TEST.prototype={
        b:{
            b1:"",
            b2:{}
        }
    };

    //Instance 1
    var first=new TEST();
    first.b.b1="TEXT";

    //Instance 2
    var second=new TEST();

    console.log("Result",second.b.b1);

Console log will output "TEXT", and I want "". So I am wondering why I get this result, and why do it change the "TEST" prototype (that's my main issue), when creating a new instance and then set values?

I got help from Bergi and Mykola (Thanks) and a duplicate. But I still think I lost a resource by this behavior, and wondering why it is build this way? It is not necessary to update prototype when working on a instance.

Oddis
  • 3
  • 3

1 Answers1

1

Methods and properties add in prototype inherits for all instances. So when you change value in prototype object, you change this for all instances.

In order to fix this. You need to set value in constructor, so it would init different value for each instance.

This will output what you want.

TEST=function(){
  this.b ={
        b1:"",
        b2:{}
    }
};
TEST.prototype.forAll = "im global";
//Instance 1
var first=new TEST();
first.b.b1="TEXT";

//Instance 2
var second=new TEST();

console.log("Second",second.b.b1, second.forAll);
console.log("First",first.b.b1, first.forAll);

Hope this helps.

Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24
  • Thanks a lot, i will rebuild my constructor. But I can't understand the logic why first.b.b1 and first.__proto__.b.b1 and window.TEST.prototype.b.b1 are the same? – Oddis Dec 04 '16 at 13:00
  • 1
    @Oddis Because there's only one object, and `TEST.prototype.b` and `first.b` and `second.b` are all pointing to it – Bergi Dec 04 '16 at 13:02
  • Thanks to Bergi and Mykola, and I accept that. But I think I lost a resource by this behavior. Thanks again. – Oddis Dec 04 '16 at 13:21