I am learning about JS Prototype.
If I set a prototype of a constructor(A) from an instance of some other constructor(B), Is that instance (of B) would introduced shared properties in A?
Example 1
function A(){
var private = '';
this.getPrivate = function(){
return private
};
this.setPrivate = function(_private){
private = _private;
};
}
function B(){};
B.prototype = new A();
b1 = new B();
b2 = new B();
b1.setPrivate(new Date());
b2.getPrivate(); // Here `private` is behaving as singleton property. Why?
Example 2
function A(){
var private = '';
}
A.prototype.getPrivate = function(){
return this.private
};
A.prototype.setPrivate = function(_private){
this.private = _private;
};
function B(){};
B.prototype = new A();
b1 = new B();
b2 = new B();
b1.setPrivate(new Date());
b2.getPrivate(); // This time private is not singleton property.
I discovered this new aspect of prototype while playing with it.
- In example 1, why
privateproperty is shared among different instances ofB? - In example 2, why
privateproperty has independent presence in both instances? However original property is unchanged but the getter/setter are defined via prototype. - Can example 1 be considered an implementation of singleton properties?
- Prototyping via instance and prototyping via prototype, What are the difference? e.g.
B.prototype = new A();
B.prototype = (new A()).constructor.prototype - What are the complete secrets of prototyping?
Because you are inheriting a specific instance locked down to specific closures. The data is owned by
the closures and not the object. There is a huge difference between variables and properties of object.
The
var privateis not used here at all. When yousetPrivate()the property is created at that point.No it’s just accidental because of misunderstanding between closures and object model. You can do the same
in a much more deliberate and clearer way: by using a simple object literal.
The difference is that in first one you get a new object, where as in second one you have
A.prototype === B.prototypeso modifyingone will modify the other since they reference the same object.
Objects inherit from other objects
Here’s a good resource https://developer.mozilla.org/en/JavaScript/Guide/Details_of_the_Object_Model