Skip to content
Advertisement

Javascript prototype from instance

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/

Advertisement

Answer

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/

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement