Skip to content

Instantly share code, notes, and snippets.

@gfx
Forked from kazuho/gist:2011480
Created March 10, 2012 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfx/2011642 to your computer and use it in GitHub Desktop.
Save gfx/2011642 to your computer and use it in GitHub Desktop.
function Base(x) {
// override properties in prototype if necessary
if (arguments.length == 1) {
this._x = x;
}
}
Base.prototype = {
_x: [],
push: function(v) { this._x.push(v) }
};
function Derived(x) {
// override properties in prototype if necessary
if (arguments.length == 1) {
Base.call(this, x);
}
}
Derived.prototype = new Base([]); // default value of _x is [] for Derived
var a = new Derived(), b = new Derived();
// 両方とも同じDerived.prototype._xに対して操作してしまう!
a.push(10);
b.push(20);
console.log(a.__proto__); // { _x: [ 10, 20 ] }
console.log(b.__proto__); // { _x: [ 10, 20 ] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment