javascript: new instance.constructor() equivalent to new Cla



给定以下代码

function Class(){}
Class.prototype=...
var instance1=new Class();

以下 2 行是否等效? 第 1 行有什么不方便的地方(性能、兼容性......

var instance2=new instance1.constructor();
var instance2=new Class();

编辑:

使用继承时,我对构造函数方法特别感兴趣:从基类中获取最终的类构造函数(如果需要,我可以举个例子)

默认情况下,它们是等效的,但这不能保证保持不变。

定义 Class 时,将自动定义Class.prototype.constructor。但是,如果您要编写一些更改原型的代码:

Class.prototype = {};

然后 Class.prototype.constructor 将回退到 Object.prototype.constructor 。那么它将对应于new Object(),而不是new Class()

回顾一下:

function Class() {}
var instance1 = new Class();
Class === instance1.constructor; // true
Class.prototype = {};
var instance2 = new Class();
instance1.constructor === instance2.constructor // false
Object === instance2.constructor // true

经过一些调查,我可能已经找到了答案。

不建议使用constructor,主要是因为人们通常通过以下操作实现继承:

Child.prototype=Object.create(Base.prototype)

这使得childInstance.constructor等于Base =>而不是通常预期的

解决办法:要避免此问题,可以添加以下行:

Child.prototype.constructor=Child

然后,我们childInstance.constructor

等于预期的Child

最新更新