在Object.create之后,instanceOf是否被破坏?

时间:2014-02-20 13:38:38

标签: javascript

我试图像往常一样用Object.create做一些继承。但是前几天我重新确定了,constructor也是prototype的属性,所以我的子实例看起来像是父实例。好吧没什么大不了的,我试着修复它,这里是代码片段:

var Parent = function() {
}

var Child = function() {
    Parent.apply(this, arguments);
}

Child.prototype = Object.create(Parent.prototype);
// now I tried to fix that bad constructor
Child.prototype.constructor = Child;

一切都很好:

var first = new Child();
first.constructor === Child; // true
first.constructor === Parent; // false

然后我发现:

first instanceof Child; // true
first instanceof Parent; // true - HUH?!?

我的意思是,这很好,但我不明白它发生在哪里。 有人可以解释一下吗?谢谢

1 个答案:

答案 0 :(得分:3)

  

这很好,但我不明白它发生在哪里。有人可以解释一下吗?

instanceof operator.constructor属性没有任何关系 - 它只检查原型链。您使用Object.create正确设置的是Parent.prototype.isPrototypeOf(first)

相关问题