假设我们有以下内容:
function Super() {
// init code
}
function Sub() {
Super.call(this);
// other init code
}
Sub.prototype = new Super();
var sub = new Sub();
然后,在ocde的其他部分,我们可以使用以下任一项来检查关系:
sub instanceof Super;
或
Super.prototype.isPrototypeOf( sub )
无论哪种方式,我们都需要有对象(子)和父构造函数(Super)。那么,你有什么理由用其中一个来对抗另一个吗?是否还有更清楚区分的其他情况?
我已经仔细阅读了2464426,但没有找到足够具体的答案。
发布于 2013-08-20 11:41:29
假设您不在代码中使用构造函数,而是使用Object.create
生成具有特定原型的对象。您的程序可能被设计为完全不使用构造函数:
var superProto = {
// some super properties
}
var subProto = Object.create(superProto);
subProto.someProp = 5;
var sub = Object.create(subProto);
console.log(superProto.isPrototypeOf(sub)); // true
console.log(sub instanceof superProto); // TypeError
在这里,您没有可与instanceof
一起使用的构造函数。您只能使用subProto.isPrototypeOf(sub)
。
发布于 2013-08-20 11:50:08
当您使用构造函数时,这几乎没有什么区别。也许instanceof
有点干净。但当你不.
var human = {mortal: true}
var socrates = Object.create(human);
human.isPrototypeOf(socrates); //=> true
socrates instanceof human; //=> ERROR!
因此,isPrototypeOf
更具有普遍性。
发布于 2014-09-21 03:17:50
var neuesArray = Object.create(Array);
Array.isPrototypeOf(neuesArray); // true
neuesArray instanceof Array // false
neuesArray instanceof Object // true
Array.isArray(neuesArray); // false
Array.prototype.isPrototypeOf(neuesArray); // false
Object.prototype.isPrototypeOf(neuesArray); // true
你明白我朋友的意思吗?)-很简单
https://stackoverflow.com/questions/18343545
复制相似问题