JavaScript:instanceof 运算符

标签 javascript prototype

第一个代码:

function MyConstructor() {}
var myobject = new MyConstructor();
MyConstructor.prototype = {};

[ myobject instanceof MyConstructor,   // false - why?
myobject.constructor == MyConstructor, // true
myobject instanceof Object ]           // true

即使 MyConstructor.prototype 被替换 myobject 仍然继承 Myconstructor.prototype 的属性。那么为什么 myobject instanceOf Myconstuctor 是假的呢?

function MyConstructor() {}
MyConstructor.prototype = {};
var myobject = new MyConstructor();
myobject instanceof MyConstructor  // true (it is because myobject still inherits from
                                   // Myconstructor.prototype although it has been replaced)

第二个:

 function MyConstructor() {}
 MyConstructor.prototype = {};
 var myobject = new MyConstructor();

 myobject.constructor == MyConstructor;  // false (accepted )

所以如果 myobject.constructor 是 Object 为什么第一个:示例不指向它,myobject.constructor 怎么可能仍然指向 MyConstructor 因为 Myconstructor.prototype 在第一个示例中发生了变化。

你能澄清一下吗?

最佳答案

even though MyConstructor.prototype is replaced myobject still inherits the properties from Myconstructor.prototype.

没有。它继承自被替换的旧对象。由于该对象是 !== MyConstructor.prototypeinstanceof operator会产生错误。在您的第二个示例中,myobject 继承自新原型(prototype)(当前的 MyConstructor.prototype),这就是 instanceof 告诉您的内容。

So if myobject.constructor

constructor 属性与 instanceof 完全无关。

function Constructor() {}
var oldProto = Constructor.prototype;
var oldInstance = new Constructor();

Constructor.prototype = {constructor:"something else"};
var newProto = Constructor.prototype;
var newInstance = new Constructor();

// all these are true:
Object.getPrototypeOf(oldInstance) === oldProto;
Object.getPrototypeOf(newInstance) == newProto;
oldProto !== newProto;
oldProto.constructor === Constructor; // was set implicitly on creating the function
oldInstance.constructor === oldProto.constructor; // inherited
newProto.constructor === "something else"; // if not explicitly set, comes from Object.prototype
newInstance.constructor === newProto.constructor; // inherited

Constructor.prototype === newProto;
newInstance instanceof Constructor; // because the above

Constructor.prototype !== oldProto;
! (oldInstance instanceof Constructor) // because the above

关于JavaScript:instanceof 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14568239/

相关文章:

javascript - 我的引导模式不工作

javascript - 为什么 JS 原型(prototype)方法可以在没有 .cal() 或 .apply() 的情况下工作?

javascript - 在 jayData 中使用自定义实体的最佳实践是什么?

javascript - 升级后的 Excel 和现在的 Visual Studio 不允许我运行我的加载项项目

javascript - joomla 的 float 模块,就像 WordPress 中一样

javascript - 如何在coffeescript :的 Angular 非类 Controller 中使用 'this'

javascript - 在 JavaScript 中使用日期时如何强制英国夏令时 (UTC+1)?

javascript - 使用构造函数添加方法

javascript - 在JavaScript中使用 'prototype'和 'this'?

Javascript 对象从自身调用函数