Skip to content

Instantly share code, notes, and snippets.

@gfx
Forked from kazuho/gist:2011480
Created March 10, 2012 14:47
Show Gist options
  • Select an option

  • Save gfx/2011642 to your computer and use it in GitHub Desktop.

Select an option

Save gfx/2011642 to your computer and use it in GitHub Desktop.

Revisions

  1. gfx revised this gist Mar 10, 2012. 2 changed files with 31 additions and 19 deletions.
    19 changes: 0 additions & 19 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -1,19 +0,0 @@
    function Base(x) {
    // override properties in prototype if necessary
    if (arguments.length == 1) {
    this._x = x;
    }
    }

    Base.prototype = {
    _x: 1
    };

    function Derived(x) {
    // override properties in prototype if necessary
    if (arguments.length == 1) {
    Base.call(this, x);
    }
    }

    Derived.prototype = new Base(3); // default value of _x is 3 for Derived
    31 changes: 31 additions & 0 deletions k.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    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 ] }

  2. @kazuho kazuho created this gist Mar 10, 2012.
    19 changes: 19 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    function Base(x) {
    // override properties in prototype if necessary
    if (arguments.length == 1) {
    this._x = x;
    }
    }

    Base.prototype = {
    _x: 1
    };

    function Derived(x) {
    // override properties in prototype if necessary
    if (arguments.length == 1) {
    Base.call(this, x);
    }
    }

    Derived.prototype = new Base(3); // default value of _x is 3 for Derived