I am confused with the following prototype behavior in javascript.
function A(){
};
A.prototype.toString = function(){
console.log('first');
}
var a = new A(), b;
A.prototype = {
toString:function(){
console.log('second');
}
}
b = new A();
a.toString();
//outputs : first
b.toString();
//outputs : second
Why does a.toString still prints "frist" when compared to b.toString which prints "second". can anyone please explain what i am missing here.
The prototype link has nothing to do with the constructor that constructed the object, it is stored on objects themselves.
When you call new A()
this happens:
var a = {};
a.__proto__ = A.prototype;
A.call(a);
Note that the above is not standard syntax but does work in chrome and firefox.
So when you overwrite A.prototype
, a.__proto__
is still linking to the old A.prototype
as you would expect with similar
code:
var A = 10, a, b;
a = A;
A = 7; //a is still 10
b = A;
I don't recommend reassigning the prototype, because then you need to re-establish the constructor property and it requires additional level of indentation.
If you want to type less, just store reference to the prototype:
function A() {
}
var fn = A.prototype;
fn.toString = function() {
};
fn.valueOf = function() {
};
fn.toJSON = function() {
};