function Foo() {}
function Bar() {}
Bar.prototype = new Foo()
console.log("Bar.prototype.constructor === Foo ? "
+ (Bar.prototype.constructor === Foo))
console.log("new Bar() instanceof Bar? "
+ (new Bar() instanceof Bar))=> Bar.prototype.constructor === Foo ? true
=> new Bar() instanceof Bar? true为什么"instanceof“结果不是"false",因为”构造函数“不是引用自身,而是引用继承的原型?
发布于 2013-06-13 21:23:23
instanceof不使用constructor属性。它在内部调用§15.3.5.3 of the specification中描述的function对象的[HasInstance]方法。
它将对象的原型(以及对象的原型等)与函数的prototype属性进行比较。
一个类似的实现是:
function myInstanceOf(obj, Constr) {
// get prototype of object
var proto = Object.getPrototypeOf(obj);
// climb up the prototype chain as long as we don't have a match
while (proto !== Constr.prototype && proto !== null) {
proto = Object.getPrototypeOf(proto);
}
return proto === Constr.prototype;
}据我所知,任何内部方法都不使用constructor属性,只有用户生成的代码使用它。
发布于 2013-06-13 21:19:49
Bar.prototype = new Foo()因此
Bar.prototype instanceof Foo因此
Bar.prototype.contructor === Foo构造函数返回对实际函数的引用
的实例
instanceof和构造函数属性之间的区别(除了明显的语法区别)是instanceof检查对象的原型链。
所以:
=> new Bar() instanceof Foo? true
=> new Bar() instanceof Bar? true
=> new Bar() instanceof Object? true以上都是事实。
https://stackoverflow.com/questions/17087977
复制相似问题