By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,598 Members | 1,897 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,598 IT Pros & Developers. It's quick & easy.

setting an object's prototype directly?

P: n/a
Hi all,

I was hoping I could do something like this in javascript:

var a = {x:1, y:2};
var b = {x:2, z:3};
b.prototype = a;

And then:

b.x => 2
b.y => 2
b.z => 3

The purpose is to set up "b" as an override of "a".

I know it doesn't work that way because "prototype" is not a magic
property on any object but constructors only. Is there a way to
implement the above without involving a constructor?

Thanks!

Jun

Oct 14 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
jy******@gmail.com wrote:
I was hoping I could do something like this in javascript:

var a = {x:1, y:2};
var b = {x:2, z:3};
b.prototype = a;

And then:

b.x => 2
b.y => 2
b.z => 3
The purpose is to set up "b" as an override of "a".

I know it doesn't work that way because "prototype" is not a magic
property on any object but constructors only. Is there a way to
implement the above without involving a constructor?


Ok , I see what your after, but I'm not sure which answer to give you.
perhaps you could explain more about what your doing.

var a = {x:1, y:2 };
var b = {x:2, y:a.y ,z:3 };

--
--.
--=<> Dr. Clue (A.K.A. Ian A. Storms) <>=-- C++,HTML, CSS,Javascript
--=<> Internet Programming since 1994 <>=-- DHTML NSAPI TCP/IP
--=<> http://resume.drclue.net <>=-- AJAX, SOAP, XML, HTTP
--=<> http://www.drclue.net <>=-- SERVLETS,TCP/IP, SQL
--.
Oct 14 '05 #2

P: n/a
The purpose is to "mark up" / "annotate" / override an object. If I
have a = {x:1, y:2} but want to pass on x:2, I want to create b = {x:2}
with its prototype pointing to a and pass it on so that client gets x:2
from b while getting the rest from a.

Jun

Oct 17 '05 #3

P: n/a
jy******@gmail.com wrote:
Hi all,

I was hoping I could do something like this in javascript:

var a = {x:1, y:2};
var b = {x:2, z:3};
b.prototype = a;

And then:

b.x => 2
b.y => 2
b.z => 3

The purpose is to set up "b" as an override of "a".

I know it doesn't work that way because "prototype" is not a magic
property on any object but constructors only. Is there a way to
implement the above without involving a constructor?

b = new ( ( a = function ( ) { } ).prototype = a );

a.y = 2;
b.x = 1;

alert( [ a.x, b.y ] );

// </joke>
but no, in all seriousness... I'm not aware of a way to do this without
a constructor. The above does work, but it still involves a
constructor.

Wish I had a real answer for you.

--
-r
(also, sorry if the joke was inappropriate)

Oct 17 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.