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 o I use this syntax:
var u = Object.create( o );
console.log( u.name );//prints Jack
u.name = "Jill";
console.log( u.name );//prints Jill
Works fine! No problem. But now at runtime I want to change the prototype of u to something else. If u was created with a constructor like this:
function U () {}
U.prototype.name = "Jack";
var u = new U;
console.log( u.name );//prints Jack
OR
function U () {
this.name = "Jack";
}
var u = new U;
console.log( u.name );//prints Jack
But when using constructors, I can totally change the prototype:
function U () {}
//totally changed the prototype object to another object
U.prototype = {
dad : "Adam"
}
var u = new U;
console.log( u.dad );//prints Adam
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?
Please provide the simplest solution which has a clean and short syntax. I just wanna know if it’s possible to do this manually. I don’t want to use the non-standard __proto__ keyword either.
I’ve searched Stackoverflow and this is not really a duplicate of the following questions:
Because I want to change the prototype after creation in a standard way (if possible). Something like Object.setPrototype() would be perfect, but that function doesn’t exist! Is there any other way to simply set the prototype of an object that is created using object literal initialization?
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:
Getting back to your question:
By modifying the object you passed into
Object.createas the prototype, as above. Note how addingbar1top1made it available ono, even thoughowas created before it was added. Just as with constructor functions, the prototype relationship endures,odoesn’t get a snapshot ofp1as 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.