Re: [JSON] Changing the class of an object after its construction
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: [JSON] Changing the class of an object after its construction

From: Thomas 'PointedEars' Lahn <PointedEars@web.de>
Date: Sun Nov 20 2005 - 15:47:05 CET

Raphael Jolivet wrote:

First of all, there are no classes in JavaScript < 2/JScript < 7/ECMAScript
< 4. Those are object-oriented programming languages using prototype-based
inheritance.

> obj1 = {
> a : 1
> b : 2
> }
>
> Then, serialized in a string :
> "{a : 1, b:2}";
>
> To get the object back (when loading it from prefrences), i do almost :
> obj1 = eval("[a:1,b:2");
               ^^^^^^^^
This will yield a syntax error. Is that why you wrote "almost"?
 
> Ok, my object is now back, but actually, the source object was
> a 'myClass' object, with lot of cool methods in it.
>
> What if I want my new object to have all these cool methods ?

You have to add `myClass' into the object's prototype chain.
Right now only `Object' is in its prototype chain as due to
the Object literal, Object() was the constructor implicitly
used.

> I've tried
> obj1.prototype = new myClass();
> But it doesn't work.

"Does not work" is a useless error description. [psf 4.11]

In fact, it MUST NOT work. `obj1' does not refer to a constructor
(i.e. a Function object), so that does not have a `prototype' property.
You are creating one with no intrinsic functionality here.

To make the prototype chain work, you need another prototype.
I found two ways for this:

a)
obj1.__proto__ = new myClass(); // JavaScript only, preserves properties

b)
obj1 = new myClass(); // works everywhere but perhaps resets properties
myClass.call(obj1); // I am not sure about that

HTH

PointedEars
Received on Mon Nov 21 03:36:35 2005