我是 JavaScript 初学者,目前正在阅读 Thomas A. Powell 和 Fritz Schneider 编写的完整引用书第三版。
I quote an extract from the same book regarding the difference b/w The constructor Property and instanceof Operator. The difference is subtle, though. The instanceof operator will recursively check the entire internal prototype chain (meaning all the ancestor types), whereas the constructor check as shown will only check the immediate object instance’s property. This ancestral checking is often very useful in inherited programming patterns with many layers of inheritance:
function Robot(){
}
function UltraRobot(){
}
var robot = new Robot();
var guard = new UltraRobot();
alert(robot.constructor == Robot); // true
alert(guard.constructor == UltraRobot); // true
guard.constructor = Robot; // Set up inheritance
alert(robot instanceof Robot); // true
alert(guard instanceof UltraRobot); // true
alert('Here');
alert(guard instanceof Robot); // true, through Inheritance
alert(guard instanceof Object); // true, all objects descend from Object
但是,作者书中的以下行,
alert(guard instanceof Robot); // true, through Inheritance
对我来说,结果是false,这让我猜测instanceof运算符将如何<强>递归地检查整个内部原型(prototype)链。
最佳答案
使用Object.create()实现经典的继承。
function Robot(){
}
function UltraRobot(){
Robot.call(this);
}
UltraRobot.prototype = Object.create(Robot.prototype);
var robot = new Robot();
var guard = new UltraRobot();
alert(guard instanceof Robot); // true, through Inheritance
关于javascript - 通过构造函数Property和instanceof操作符设置继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27909353/