In other words are these two different blocks of code fully equivalent?
ES6 class extend based
class Child extends Parent {
// Define my subclass
}
var myInstance = new Child();
Object.assign based
var myInstance = Object.assign(new Parent(), {
// Define my subclass
}
In my particular use case I am trying to extend (Facebook's) Flux Dispatcher. In their examples they use Object.assign. I would like to ES6 class extend, but I am worried that there are subtle differences between the two so I should stick with Object.assign.
No, these code blocks are not equivalent
In the class inheritance example you will get a new constructor which makes objects having features from parent class.
Extending objects via Object.assign
is a example of mixins.
You just add some properties to one instance but not change all future children.
Unlike child classes, an instance after extension will still have the constructor
property pointing to the Parent
. It means that you can't recognize extended child among non-extended, because they all have the same constructor and operator instanceof
will give the same result. Also you can't get access to overridden methods in child, because you will lose the link to it.
As for flux's dispatcher in this example, you can't extend it via class inheritance, because there is no constructor which you can provide as a parent.