Skip to content Skip to sidebar Skip to footer

Changing Prototype Of An Object Which Was Created With Literal Initialization

Let's say I want to use ONLY object literals (not constructors). I have an object like this: var o = { name : 'Jack' } If I want to create another object which its prototype is

Solution 1:

With the current spec, you can't change an object's prototype once it's instantiated (as in, swap out one and swap in another). (But see below, things may be changing.) You can only modify the object's prototype. But that may be all you want, looking at your question.

To be clear about the distinction:

var p1 = {
    foo1: function() {
        console.log("foo1");
    }
};
var p2 = {
    foo2: function() {
        console.log("foo1");
    }
};

var o = Object.create(p1);
o.foo1(); // logs "foo1"
o.foo2(); // ReferenceError, there is no foo2
// You cannot now *change* o's prototype to p2.
// You can modify p1:
p1.bar1 = function() { console.log("bar1"); };
// ...and those modifications show up on any objects using p1
// as their prototype:
o.bar1(); // logs "bar1"
// ...but you can't swap p1 out entirely and replace it with p2.

Getting back to your question:

If u was created with a constructor like this...Then whatever I added to the prototype of U would automatically be added to every object that is created after those changes. But how do I get the same effect with Object literals?

By modifying the object you passed into Object.create as the prototype, as above. Note how adding bar1 to p1 made it available on o, even though o was created before it was added. Just as with constructor functions, the prototype relationship endures, o doesn't get a snapshot of p1 as of when it was created, it gets an enduring link to it.


ES.next is looking likely to have the "set prototype operator" (<|), which will make it possible to do that. But there's no standard mechanism for it currently. Some engines implement a pseudo-property called __proto__ which provides this functionality now, but it's not standardized.


Post a Comment for "Changing Prototype Of An Object Which Was Created With Literal Initialization"