为什么 `instanceof` 会产生不同的结果?

Why is `instanceof` producing different results?

为什么 instanceof 运算符在以下两段代码中产生不同的结果,它在幕后是如何工作的?

1>

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

myobject instanceof MyConstructor 
**true**

2> 现在如果我执行下面的代码,结果是不同的:

MyConstructor.prototype = {};
myobject instanceof MyConstructor 

**false**

你能解释一下运算符实例是如何工作的吗?我了解原型继承在 javascript 中的工作原理,但我无法理解这种场景。

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

因此,如果您重新分配原型,myobject 的原型将不会 === 到(新的)MyConstructor.prototype,因此 instanceof 解析为 false.

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

console.log(myobject instanceof MyConstructor);
console.log(Object.getPrototypeOf(myobject) === MyConstructor.prototype);

MyConstructor.prototype = {};
console.log(myobject instanceof MyConstructor);
console.log(Object.getPrototypeOf(myobject) === MyConstructor.prototype);