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.
private
property is shared among different instances of B
?private
property has independent presence in both instances? However original property is unchanged but the getter/setter are defined via prototype.B.prototype = new A();
B.prototype = (new A()).constructor.prototype
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 private
is not used here at all. When you setPrivate()
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.prototype
so modifying
one 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