Until today, I was completely unaware of this issue and now I am eager to discover the most effective way to navigate around it. The problem arises when two distinct objects are instantiated from the same constructor function - they end up sharing the same prototype. This results in a scenario where altering the prototype of one object affects all other objects as well.
Let's take a look at an example:
function A(obj) {
}
A.prototype = {
events: {
one: 1
}
};
var b = new A();
console.log(b.events);
var c = new A();
console.log(c.events);
b.events.x = 2;
console.log(b.events);
console.log(c.events); //oops, c also inherited x from b
What a confusing situation! Is there a superior method to work around this?
I proposed a solution below, but I'm curious if there is a more efficient approach:
var _ = require('underscore');
function A(obj) {
if (obj == null) {
obj = {};
}
if(obj.events == null){
obj.events = {};
}
this.events = _.extend(obj.events, A.prototype.events);
}
A.prototype = {
events: {
one: 1
}
};
var b = new A({events:{three:3}});
console.log(b.events);
var c = new A({events:{four:4}});
console.log(c.events);
b.events.x = 2;
console.log(b.events);
console.log(c.events); //now it's improved...(quite puzzling)