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?