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: Rob Williscroft <rtw@freenet.co.uk>
Date: Sun Nov 20 2005 - 20:24:44 CET

Raphael Jolivet wrote in news:ux%ff.1569$gC1.880@nntpserver.swip.net in
comp.lang.javascript:

> What if I want my new object to have all these cool methods ?
> I've tried
> obj1.prototype = new myClass();
> But it doesn't work.
>

<script type="text/javascript">
/** Copy an object to a new func()
*/
function copy_json( func, src )
{
  var f = function() {}
  f.prototype = func.prototype;
  var dest = new f();
  for ( var i in src ) dest[i] = src[i];
  return dest;
}

/** Sample data
*/
var ob =
{
  a : 1, b : 2, c : 3
};

/** Sample type with a prototype method
*/
function MyObject()
{
  this.a = this.b = this.c = -1;
  return this;
}
MyObject.prototype.upper = function()
{
  return "{A:" + this.a + ",B:" + this.b + ",C:" + this.c + "}";
}

/** Does it work
*/
function test()
{
  var copy = copy_json( MyObject, ob );

  alert( copy.upper() + "\n" + (new MyObject()).upper() );
}
</script>

Rob.

-- 
http://www.victim-prime.dsl.pipex.com/
Received on Mon Nov 21 03:36:51 2005