javascript - 通过构造函数Property和instanceof操作符设置继承

标签 javascript inheritance constructor instanceof

我是 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/

相关文章:

javascript - SVG 过滤器动画问题

javascript - 在使用 ajax 提交时,在 greasemonkey 用户脚本中将文本附加到表单

Javascript:排序对象

c++ - 派生类中的基指针地址如何?

c++ - arb 的静态 ctor/dtor 观察器。 C++类

javascript - 当 div 中的输入元素处于焦点状态时按下 Enter 键时会重复 div

c++ - 在指针类中引用虚函数时出现段错误

java - 这个 UML 图中的包外观图标是什么意思?

c++ - 为什么我收到错误: “there is more than one default constructor” ?

iOS 对多个 ViewController 使用相同的 xib