简体   繁体   中英

why prototype allow multiple instances share variables?

Say,

function Person(name) {
    this.name = name;
}

Person.prototype.share = [];

Person.prototype.printName = function() {
    alert(this.name);
}

var person1 = new Person('Byron');
var person2 = new Person('Frank');

person1.share.push(1);
person2.share.push(2);
console.log(person2.share); //[1,2]

In the above, share can be used by all instances. I am wondering if this is specific to Javascript? anything similar for other OOP language like C++, C# or Java?

Because that's how prototypes work.

In classical OOP (Java, C# etc.), classes are just "templates", and inheritance is just combining the "templates" for instances to be created from. In prototypal inheritance, an instance is an object whose parent is a live object . They don't just share definition, they share the same live instance of a parent.

So why does it work? That's because of how prototype lookups work. If some property isn't found in the instance, the engine looks for it in the parent. If still not there, it looks higher up in the prototype chain until it reaches the root object. If still not there, the engine can declare it undefined (if it's a property lookup) or throw an error (if you called a method).

instance -> parent -> parent -> parent -> Object

That's how JS "inherits". It basically just looks for the ancestor that has that something you want, and operate at that level. This is why instances of Person can push to share , because they have a common parent object.

person1
        \
         > Person.prototype (which has share[])
        /
person2

In order to prevent such sharing, one can override it by declaring a share property in the constructor (which when instantiated, creates one per instance). Another is just putting a share property on the instance. Descendant properties take precedence over ancestor properties, since lookup starts from the bottom.

function Person(name) {
    this.name = name;
    this.share = []; // Instances will have share, but not shared anymore
}

// or 
person1.share = []; // Creates a share for person1 only

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM