简体   繁体   English

在javascript中将构造函数添加回object.create的最佳方法

[英]best way to add back constructor to object.create in javascript

I am fully aware of other very similar posts about object.create but I really cannot arrive to answer on this particular question. 我完全了解关于object.create的其他非常相似的帖子,但是我真的无法回答这个特定的问题。 I saw a code once where it looks like it was using object.create to create new prototype and then adding back to constructor 我曾经看到一个代码,看起来就像在使用object.create来创建新原型,然后将其添加回构造函数

function blah(){
   // typical constructor
}

blah.prototype = Object.create(somethingelse.prototype);
blah.prototype.constructor = blah;

Something like that .. and I tried that in chrome dev tool but did not see them as equal.. Now trying to see what that code I did see was trying to accomplish? 诸如此类..我在chrome开发工具中尝试了该方法,但并不认为它们是相同的。.现在尝试查看我看到的代码试图完成什么? I assume there is more difference in Object create and new(than just missing constructor?) 我认为Object create和new之间的区别更多(不仅仅是缺少构造函数?)

function blah(){
 //...
}
undefined
function somethingelse(){
 //
}
undefined
somethingelse.prototype = {
    // something else
}
Object {}
blah.prototype = Object.create(somethingelse.prototype);
Object {}
blah.prototype.constructor = blah;
blah(){
 //...
}
blah == somethingelse;
false

You've created two different objects (blah and something). 您已经创建了两个不同的对象(等等)。 I think you are confused about what inheritance means. 我认为您对继承的含义感到困惑。

when you compare (==) 2 objects the reference is being evaluated - and it is different. 当您比较(==)2个对象时,参考值正在评估-且有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM