I am a beginner to JavaScript and currently going through the The Complete Reference 3rd Edition by 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
However, the below line in the author's book,
alert(guard instanceof Robot); // true, through Inheritance
for me, results in false, which leaves me in guessing how the the instanceof operator will recursively check the entire internal prototype chain.
1 Answer 1
Use Object.create() to achieve classical inheritance.
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
Comments
Explore related questions
See similar questions with these tags.
alert(guard instanceof Robot);should be false then.Object.getPrototypeOf(guard)is stillUltraRobotso it's not an instance ofRobot. You have to change the prototype as well.