ES6类扩展是否完全等同于基于Object.assign的对象扩展? [英] Is ES6 class extend fully equivalent to Object.assign based extending of an object?

查看:176
本文介绍了ES6类扩展是否完全等同于基于Object.assign的对象扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

换句话说,这两个不同的代码块完全等效吗?

In other words are these two different blocks of code fully equivalent?

class Child extends Parent {
    // Define my subclass
}
var myInstance = new Child();

基于Object.assign

var myInstance = Object.assign(new Parent(), {
   // Define my subclass
}

在我的特定用例中,我试图扩展(Facebook的)Flux Dispatcher.在他们的示例中,他们使用Object.assign.我想扩展ES6类,但是我担心两者之间存在细微的差异,因此我应该坚持使用Object.assign.

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.

推荐答案

不,这些代码块不相同

在类继承示例中,您将获得一个新的构造函数,该构造函数使对象具有父类的功能.

In the class inheritance example you will get a new constructor which makes objects having features from parent class.

通过Object.assign扩展对象是 mixins 的示例. 您只需要向一个实例添加一些属性,而不会更改所有将来的子代.

Extending objects via Object.assign is a example of mixins. You just add some properties to one instance but not change all future children.

与子类不同,扩展后的实例仍将具有指向Parentconstructor属性.这意味着您无法识别未扩展的子级,因为它们都具有相同的构造函数,并且运算符instanceof将给出相同的结果.另外,您将无法访问child中的重写方法,因为您将失去指向它的链接.

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.

对于flux的调度程序在此示例中,您无法通过类继承对其进行扩展,因为没有可作为父级提供的构造函数.

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.

这篇关于ES6类扩展是否完全等同于基于Object.assign的对象扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆