Javascript中isPrototypeOf和instanceof有什么区别? [英] What's the difference between isPrototypeOf and instanceof in Javascript?

查看:82
本文介绍了Javascript中isPrototypeOf和instanceof有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我自己的一些旧代码中,我使用以下代码:

In some of my own older code, I use the following:

Object.prototype.instanceOf = function( iface )
{
 return iface.prototype.isPrototypeOf( this );
};

然后我做(例如)

[].instanceOf( Array )

这有效,但是似乎以下情况也是如此:

This works, but it seems the following would do the same:

[] instanceof Array

现在,这肯定只是一个非常简单的例子。因此,我的问题是:

Now, surely this is only a very simple example. My question therefore is:

b的实例 总是与<$相同c $ c> b.prototype.isPrototypeOf(a)?

推荐答案

是的,他们这样做了同样的事情,两者都遍历原型链,寻找其中的特定对象。

Yes, they do the same thing, both traverse up the prototype chain looking for an specific object in it.

两者之间的区别是它们是什么,以及如何你使用它们,例如 isPrototypeOf 一个函数 Object.prototype 对象上可用,它允许您测试特定对象是否在另一个原型链,因为这个方法是在 Object.prototype 上定义的,它可用于所有对象。

The difference between both is what they are, and how you use them, e.g. the isPrototypeOf is a function available on the Object.prototype object, it lets you test if an specific object is in the prototype chain of another, since this method is defined on Object.prototype, it is be available for all objects.

instanceof 是一个运算符,它需要两个操作数,一个对象和一个构造函数,它将测试对象链上是否存在传递的函数 prototype 属性(通过 [[HasInstance]](V) 内部操作,仅在Function对象中可用。)

instanceof is an operator and it expects two operands, an object and a Constructor function, it will test if the passed function prototype property exists on the chain of the object (via the [[HasInstance]](V) internal operation, available only in Function objects).

例如:

function A () {
  this.a = 1;
}
function B () {
  this.b = 2;
}
B.prototype = new A();
B.prototype.constructor = B;

function C () {
  this.c = 3;
}
C.prototype = new B();
C.prototype.constructor = C;

var c = new C();

// instanceof expects a constructor function

c instanceof A; // true
c instanceof B; // true
c instanceof C; // true

// isPrototypeOf, can be used on any object
A.prototype.isPrototypeOf(c); // true
B.prototype.isPrototypeOf(c); // true
C.prototype.isPrototypeOf(c); // true

这篇关于Javascript中isPrototypeOf和instanceof有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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