Q1: Why does the reassignment of the Ninja.prototype to a newly created object via the Person constructor throw off the instanceof
operator?
This does so because the instanceof
operator works by going up the prototype chain and checking whether the internal actual prototype of the object ([[Prototype]]
) compares with the current prototype property of the constructor function.
Q2: What is the correct approach to do what I'm attempting to do? In other words, create a simple object hierarchy where the properties are truly at different levels of the hierarchy, while also being able to use instanceof
in a way that makes sense?
Prototypes are meant for items that are common to all instances of a constructor (for example all people have a brain, but not everyone has the same name). Instead of changing the prototype, add the first name and last name arguments directly as properties of instances of the Ninja
function, and make the prototype property of Ninja
a blank Person
(to cover the case of a person without a name and so that instanceof
returns true):
var Person = function (firstName, lastName)
{ this.firstName = firstName;
this.lastName = lastName;
}
var Ninja = function (beltColor, firstName, lastName)
{ this.beltColor = beltColor;
Person.call(this, firstName, lastName); // call parent function
}
Ninja.prototype = new Person("", ""); // do this so that instanceof returns true
var ninja1 = new Ninja ("Black", "George", "Clooney");
var ninja2 = new Ninja ("Blue", "Scarlett", "Johansson");
var ninja3 = new Ninja ("Green", "Brad", "Pitt");
console.log (ninja1 instanceof Ninja); // true
console.log (ninja1 instanceof Person); // true
console.log (ninja2 instanceof Ninja); // true
console.log (ninja2 instanceof Person); // true
console.log (ninja3 instanceof Ninja); // true
console.log (ninja3 instanceof Person); // true