通过构造函数Property和instanceof Operator设置继承

时间:2015-01-12 19:31:09

标签: javascript inheritance constructor instanceof

我是JavaScript的初学者,目前正在阅读Thomas A. Powell,Fritz Schneider 的 The Complete Reference 3rd Edition。

  

我引用了同一本书关于差异的推文    构造函数Property和instanceof Operator 。但差别很微妙。 instanceof 运算符将会    递归检查 整个内部原型链(意为所有祖先类型) ,         而如图所示的 构造函数 检查只会检查 立即对象实例的属性 。         此 祖先检查 继承的编程模式 中通常非常有用,具有多层继承:

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 运算符将如何< strong> 递归检查 整个内部原型链

1 个答案:

答案 0 :(得分:1)

使用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