views:

33

answers:

2

I use prototypal inheritance and want to have objects with instance arrays. So if I derive some objects from one object with an instance array and access the array, all of them share the array. I want to push something to the array and only change the array in the actual object, not in all others.

What is a elegent solution to this Problem with using standard prototypal inheritance and Object.create?

var sys = require('sys');

var obj ={
    data: [],
    add: function(what){
        this.data.push(what)
    }
};

var one = Object.create(obj);
one.add(1);

var other = Object.create(obj);
other.add(2);

sys.puts(other.data.length); // is 2, but should be 1
+2  A: 
var ObjectName = function(){
    this.data = [];
}

ObjectName.prototype.add = function(what){
    this.data.push(what);
};

var one = new ObjectName();
one.add(1);
Ronald
I want to use prototypal inheritence with Object.create
Peterfia
You can still use object.create. But you have to run the constructor to initialize the object with the instance variable this.data.var one = Object.create(ObjectName.prototype);ObjectName.call(one);one.add(1);
Marco
+1  A: 

There is no elegant solution with Object.create, because You're Doing It Wrong.

What you want is:

function MyArray() {
    this.data = [];  // per-instance data here
}

MyArray.prototype = {
    add: function(what) {  // prototype methods here
        this.data.push(what);
    }
};

var one = new MyArray;
one.add(1);
...
Jason Orendorff