3

以下代码之间有什么区别:

inst instanceof Constr

inst.__proto__ === Constr.prototype

例如:

var xyz = {}
xyz instanceof Object

xyz.__proto__ === Object.prototype

? 如果是这样,有什么区别,哪个是首选?

4

4 回答 4

4

__proto__不是 ECMAScript 5 规范的一部分,并且您无法保证未来的支持。访问对象原型的标准方法是访问构造函数的原型,或者更好的是Object.getPrototypeOf(但这在 IE8 上不起作用)。

instanceof检查构造函数的原型,但也“测试对象原型链中是否存在 constructor.prototype”。.

如果您的目标是检查一个对象是否是特定类的实例,并且如果它不是直接实例对您来说没问题,那么您应该使用instanceofoperator :它实际上就是为此而生的。

于 2013-06-28T12:51:50.600 回答
2

有两个区别。正如其他人之前提到的那样instanceof是递归的。您可以实现自己的版本,instanceof如下所示:

function instanceOf(obj, func) {
    return Object.isPrototypeOf.call(func.prototype, obj);
}

此功能取决于功能的可用性Object.prototype.isPrototypeOf

第二个区别仅适用于浏览器。如以下答案中所述,浏览器中的实际实现instanceof如下:

function instanceOf(obj, func) {
    var prototype = func.prototype;

    while (obj = Object.getPrototypeOf(obj)) { //traverse the prototype chain
        if (typeof object === "xml")           //workaround for XML objects
            return prototype === XML.prototype;
        if (obj === prototype) return true;    //object is instanceof constructor
    }

    return false; //object is not instanceof constructor
}

就这样。有关更多信息,请参阅以下文档instanceofhttps ://developer.mozilla.org/en/JavaScript/Guide/Details_of_the_Object_Model#Determining_instance_relationships

于 2013-06-28T13:01:45.523 回答
1

Instanceof 进一步检查

var GrandParent=function(){};
var Parent = function(){}
Parent.prototype=new GrandParent()
var Child = function(){};
Child.prototype=new Parent()

var c=new Child();
console.log(c instanceof GrandParent);//true
console.log(c.__proto__ === GrandParent);//false
于 2013-06-28T12:54:46.160 回答
1

实际上还有第三种方式,看起来很像非标准__proto__示例:

Object.getPrototypeOf([]) === Array.prototype

疲倦:

console.log([] instanceof Object);//ture
console.log(Object.getPrototypeOf([]) === Object.prototype);//false

基本上,instanceof操作员检查整个原型链,其他方法不检查

于 2013-06-28T12:55:48.913 回答