0

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.

asked Jan 12, 2015 at 19:31
18
  • 2
    i think you're missing a line, something like UltraRobot.prototype=new Robot(); Commented Jan 12, 2015 at 19:34
  • @dandavis: No, I have checked it. Commented Jan 12, 2015 at 19:37
  • alert(guard instanceof Robot); should be false then. Commented Jan 12, 2015 at 19:38
  • You never change the prototype, just the constructor, and Object.getPrototypeOf(guard) is still UltraRobot so it's not an instance of Robot. You have to change the prototype as well. Commented Jan 12, 2015 at 19:38
  • 1
    Any book that uses alert as a debugging tool, is either too old, or is poorly written. Commented Jan 12, 2015 at 19:44

1 Answer 1

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
answered Apr 9, 2015 at 0:25
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.