2

I would like to make objects, with earlier created objects as the prototypes. This way I would be able to make additions to existing objects without modifying them.

Methods which interact with the earlier created objects (so using there attributes and perhaps mutating them) could also be applied to the newly derived objects.

I thought this could be done with the following code, but it doesn't...

objs = [];

for (var i = 0; i < 5; i++) {
    objs.push({
        index: i
    });
}

for (var i = 0; i < 5; i++) {
    var newObj = {};
    newObj.prototype = objs[i];
    alert(newObj.index);
}

http://jsfiddle.net/q5bu25L1/2/

3

2 Answers 2

1

A prototype comes into play when you use a constructor to create an instance of an object. In order to get your approach to work, you can do this:

for (var objI in objs) {
    var obj = objs[objI];
    var newObj = function() {};
    newObj.prototype = obj;
    newObj = new newObj();
    console.log(newObj.i);
}

http://jsfiddle.net/q5bu25L1/3/

Or you could just use Object.create(), which accomplishes pretty much the same thing.

Note that neither of these approaches can completely prevent the contents of the parent objects from being modified if they themselves contain objects. For example:

var a = { n: 8, myObj: { i: 7 }};
var b = Object.create(a);

b.n = 10;
console.log(a.n);  // still 8
console.log(b.n);  // 10

b.myObj.i = 15;
console.log(a.myObj.i);  // changed to 15!
console.log(b.myObj.i);  // 15

http://jsfiddle.net/0f5ydL6u/

Sign up to request clarification or add additional context in comments.

Comments

1

what about using native Object.create() ECMA5 spec

look at the full support comparison

objs = [];

for (var i = 0; i < 5; i++) {
    objs.push({
        index: i
    });
}

for (var i = 0; i < 5; i++) {
    var newObj = Object.create(objs[i]);
    alert(newObj.index);
}

DEMO

1 Comment

Note IE < 9 doesn't support this. Polyfill's are available though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.