0

Is there an easy way in JS to change a base type into a defined subtype? And does this make any sense (does anyone have any examples of when this could be used in a reasonable and useful way).

contrived example (likely with syntax errors):

var animal = function(id){
  this.init(id);
}
cat.prototype.init = function(id){this.id = id;}
cat.prototype.eat = function(){something...};

var cat = function(name, fur){
  this.fur=fur;
  this.init(id);
}
cat.prototype = new animal();

var myanimal = new animal(getNextId()); //maybe it's a petstore or something that needs animals in their DB.
//myanimal needs to become a cat now.
DanielST
  • 13,783
  • 7
  • 42
  • 65

1 Answers1

1

Is there an easy way in JS to change a base type into a defined subtype?

No. There is a complicated way though, which changes the prototype and then re-applies the subtype constructor.

And does this make any sense?

No, definitely not. You'd do things like this only to re-use objects (object pool as a performance optimisation), but altering the [[prototype]] defeats that purpose.

Just create a new instance:

myanimal = new cat(myanimal.id); // use id of old animal, and overwrite variable
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • So if my objects were more complicated, I'd do something like `myanimal = animalToNewCat(myanimal);` – DanielST Jul 08 '14 at 15:26
  • Yes, that would be advisable. Unless you've got a requirement to mutate the existing object. – Bergi Jul 08 '14 at 15:31