JavaScript isPrototypeOf vs instanceof用法 [英] JavaScript isPrototypeOf vs instanceof usage

查看:192
本文介绍了JavaScript isPrototypeOf vs instanceof用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下内容:

function Super() {
      // init code
}

function Sub() {
      Super.call(this);
      // other init code
}

Sub.prototype = new Super();

var sub = new Sub();

然后,在我们ocde的其他部分,我们可以使用以下任一方法来检查关系:

Then, in some other part of our ocde, we can use either of the following to check for the relationship:

sub instanceof Super;   

Super.prototype.isPrototypeOf( sub )

无论哪种方式,我们都需要同时拥有object(sub)和父构造函数(Super)。那么,你有没有理由使用其中一个?还有其他一些区别更明确的情况吗?

Either way, we need to have both the object (sub), and the parent constructor (Super). So, is there any reason why you'd use one vs the other? Is there some other situation where the distinction is more clear?

我已经仔细阅读 2464426 之间的差异,但没有找到足够具体的答案。

I've already carefully read 2464426, but didn't find a specific enough answer.

推荐答案

想象一下,在代码中不使用构造函数,而是使用 Object.create 生成具有特定原型的对象。您的程序可能被设计为根本不使用构造函数:

Imagine you don't use constructors in your code, but instead use Object.create to generate objects with a particular prototype. Your program might be architected to use no constructors at all:

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)

Here, you don't have a constructor function to use with instanceof. You can only use subProto.isPrototypeOf(sub).

这篇关于JavaScript isPrototypeOf vs instanceof用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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