Modifying prototype chain

A

Alexis Nikichine

One question for today: how can I reseat the (implicit) reference an
object has to its prototype ?

I know this opens up a can of worms (circular prototype chain, brrr...)
but still, that would be a neat way of replacing a whole subset of
object properties in one, quick, operation. I suspect I am dreaming out
loud, though.

Thanks in advance for any help,

Alexis
 
M

Martin Honnen

Alexis said:
how can I reseat the (implicit) reference an
object has to its prototype ?

The Spidermonkey engine (originally developed for and used in Netscape,
now part of the Mozilla open source project) exposes the prototype as
the __proto__ property e.g.

var god = { name: 'Kibo' };
alert(god.__proto__ === Object.prototype);

but other engines don't do that and you shouldn't rely on that. But you
can set the property if needed I think:

var god = { name: 'Kibo' };
god.__proto__ = {
praise : function () {
alert('All hail ' + this.name);
}
};
god.praise();


In general if you want to deal with prototypes and exploit them then
simply create your own constructor function and set its prototype e.g.

function God (name) {
this.name = name;
}
God.prototype.praise = function () {
alert('All hail ' + this.name);
};

var god = new God('Kibo');
god.praise();

that should work across engines.
 
A

Alexis Nikichine

Martin said:
The Spidermonkey engine (originally developed for and used in Netscape,
now part of the Mozilla open source project) exposes the prototype as
the __proto__ property e.g.

var god = { name: 'Kibo' };
god.__proto__ = {
praise : function () {
alert('All hail ' + this.name);
}
};
god.praise();

I had read about __proto__ before, but mistakenly believed it was read-only.

On reading your example, I prayed:

js> god.__proto__ = god;

and received this blessing:

typein:75: Error: cyclic __proto__ value

Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top