Ahmed Magdy Ahmed Magdy - 1 year ago 65
Javascript Question

A Way to move an instance to another class in javascript

I was actually practicing creating classes and instances of them using the

keyword and this came to my mind.

Suppose I have a superclass called
and I have two subclasses which are

Suppose that I have a new customer called bob ==>
var bob = new newCustomer();

and I have a special customer called smith ==>>

var smith = new specialCustomer();

How can I write a method that when assigned to bob, it moves him from being a newCustomer instance to a specialCustomer instance?

like for example, what code should I write to make this work:

bob.moveToSpecial() //moves bob from being instance of newCust to specialCust

Psi Psi
Answer Source

An object is not an instance of a class, an object has a prototype based upon the constructor called.

What you can do (although it may lead to side-effects) is changing the prototype of that object:

bob.__proto__ = specialCust.prototype;

Read about the warnings when doing this here: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/proto

A better way is to create a new object and move all properties from bob there:

newBob = new specialCust();
for(var prop in bob){
    newBob[prop] = bob[prop];

Be aware that in both cases, bob loses his "inherited" methods and properties from the old prototype, although in the latter case only the non-enumerable ones (as stated in the comments). The enumerable ones will get copied and bound to the new object directly, possibly overriding inherited methods, so be aware of that, too.

Also worth reading: https://reinteractive.com/posts/235-es6-classes-and-javascript-prototypes

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download