Understanding prototype behavior - JavaScript
I don't understand why the following is happening:
I have the following code:
singleton = (function() {
somePrivFunction = function() {
return new B();
}
A = function() {};
B = function() {};
C = function() {};
A.prototype.a = function() { console.log("a"); };
B.prototype = A.prototype;
B.constructor = B;
B.prototype.b = function() { console.log("b"); };
C.prototype = A.prototype;
C.constructor = C;
C.prototype.c = function() { console.log("c"); };
return {
someFunction: function() {
return somePrivFunction();
}
}
})();
When I call singleton.someFunction()
, it returns an instance to me B
. However, all of the following works:
singleton.someFunction().b(); // Prints "b"
singleton.someFunction().a(); // Prints "a"
singleton.someFunction().c(); // Prints "c", but why? Shouldn't it be undefined?
source to share
B.prototype
has a reference to the same object as A.prototype
(line 12). On line 16, you saved the same object reference to C.prototype
. This means that all three prototypes point to the same object, so all changes made to A.prototype
, B.prototype
or C.prototype
will actually change, the same object. At the end of your code, this object has three methods: a, b and c.
source to share