I am trying to create a simple helper function to automate javascript inheritance. Works like this:
var myClass = makeClass({
inherit: SomeSuperClass, //optional, obviously
constructor: function() {} // would like for this to be optional
anotherMethod: function(){} // just gets added to the prototype chain.
// etc
});
I have everything working wonderfully, and its pretty lightweight, but I've run across a bug that tells me I don't really understand what I'm doing. Working from the wonderful answer at https://stackoverflow.com/a/22316035/2475951 I have the following:
function makeClass(properties) {
// If the user doesn't supply a constructor, give them a generic function
if ( ! properties.constructor ){
properties.constructor = function(){};
}
if (properties.inherit) {
properties.constructor.prototype = Object.create(properties.inherit.prototype);
properties.constructor.prototype.constructor = properties.constructor;
}
return properties.constructor;
// Plus a simple loop to add the remaining methods given in properties to the prototype chain. Not important here
}
Now onto implementation. This works just as expected.
var Food = makeClass({
constructor: function(){}
});
var Bread = makeClass({
inherit: Food,
constructor: function(){}
});
var Sushi = makeClass({
inherit: Food,
constructor: function(){}
});
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
My problem comes in one either Bread or Sushi don't supply a constructor. If Bread doesn't supply a constructor, thus using the generic function created in makeClass(), then:
(sushi instanceof Bread) become **true**
If Sushi doesn't supply a constructor then bread becomes an instance of Sushi. Why is this happening? I could understand if they both evaluate to true or false, but why does removing Bread's constructor affect the sushi instance? I would imagine my problem is in assigning an empty function to properties.constructor if it is void, but I don't know how else to do this.
If what I am wanting to do is not possible, or not best practice, I would like to know that too. Still, it seems like I'm missing something pretty basic. I've searched around SO and google for hours, and can't seem to find this same problem.
Thanks!