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/

Benjamin
  • 343
  • 6
  • 12
  • 2
    you might need to look at [`Object.create(objs[i])`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) – code-jaff Aug 12 '14 at 11:50
  • possible duplicate of [Prototypical inheritance - writing up](http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up) – Barun Aug 12 '14 at 11:51
  • 2
    you might want to have a look at [`__proto__` VS. `prototype` in JavaScript](http://stackoverflow.com/q/9959727/1048572) – Bergi Aug 12 '14 at 12:05

2 Answers2

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/

JLRishe
  • 99,490
  • 19
  • 131
  • 169
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

code-jaff
  • 9,230
  • 4
  • 35
  • 56
  • 2
    Note IE < 9 doesn't support this. [Polyfill's are available](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill) though. – Matt Aug 12 '14 at 11:55