I\'ve seen a lot of stuff like this, and am looking for the proper solution to basic JavaScript inheritance:
function Food(){} // Food constructor (class)
Lets examine your code a little bit.
function Food(){}
function Bread(){}
function Sushi(){}
var basicFood = new Food();
Bread.prototype = basicFood;
Sushi.prototype = basicFood;
Note: When you set the same object as the prototype of two objects, augmentation in one prototype, will reflect in the other prototype as well. For example,
Bread.prototype = basicFood;
Sushi.prototype = basicFood;
Bread.prototype.testFunction = function() {
return true;
}
console.log(Sushi.prototype.testFunction()); // true
Lets get back to your questions.
var bread = reconstructify(new Bread(), Bread);
var sushi = reconstructify(new Sushi(), Sushi);
console.log(sushi instanceof Bread); // Why true?
console.log(bread instanceof Sushi); // Why true?
As per the instanceof docs from MDN,
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
So when we do something like
object1 instanceof object2
JavaScript will try to find if the prototype of the object2
is in the prototype chain of object1
.
In this case, it will return true
only when the Bread.prototype
is in the prototype chain of sushi
. We know that sushi
is constructed from Sushi
. So, it will take Sushi
's prototype and check if it is equal to Bread
's prototype. Since, they both point to the same basicFood
object, that returns true
. Same case for, bread instanceof Sushi
as well.
So, the right way to inherit would be, like this
function Food() {}
function Bread() {}
function Sushi() {}
Bread.prototype = Object.create(Food.prototype);
Bread.prototype.constructor = Bread;
Sushi.prototype = Object.create(Food.prototype);
Sushi.prototype.constructor = Sushi;
var bread = new Bread();
var sushi = new Sushi();
console.log(sushi instanceof Bread); // false
console.log(bread instanceof Sushi); // false
console.log(sushi.constructor); // [Function: Sushi]
console.log(bread.constructor); // [Function: Bread]
console.log(sushi instanceof Food); // true
console.log(bread instanceof Food); // true
console.log(sushi instanceof Sushi); // true
console.log(bread instanceof Bread); // true