In javascript how would I set up inheritance so that static and instance properties/methods are inherited?
My goal is to build a base "class" that 3rd parties would inherit from, and be able to call static and instance properties/methods inherited from the base "class".
In my example I define a recipe base class that others can inherit from and create recipes off of:
Function.prototype.inherits = function (base) {
// code to inherit instance and static
// props/methods here
var temp = function () { };
temp.prototype = base.prototype;
this.prototype = new temp();
}
function Recipe() {
var self = this;
Recipe.ingredients = { };
Recipe.prepare = function (ingredients) {
// prepare each of the ingredients...
var preparedIngredients = ingredients;
Recipe.ingredients = preparedIngredients;
};
self.share = function () {
console.log('Recipe Shared!');
};
}
Toast.inherits(Recipe);
function Toast() {
var self = this;
}
var toast = new Toast();
// Child function should inherit static methods
Toast.Prepare({
bread: '2 slices',
butter: '1 knob',
jam: '1 tablespoon'
});
// Child function should inherit static properties
console.log(Toast.ingredients);
// Child function should inherit instance methods as well
toast.share();
// And if I define another it gets its own static properties/methods
// Spaghetti.ingredients !== Toast.ingredients
Spaghetti.inherits(Recipe);
function Spaghetti() {
var self = this;
}
Spaghetti.prepare({
noodles: '1 box',
tomatoes: 2,
sausage: 1
});
Plnkr here: http://plnkr.co/edit/x8rKeKXSxDHMB4CD6j1c
Here's an example of static/instance member inheritance. This is using small class framework I wrote to make oop in javascript easier to use and nicer to look at. It's available on github if you are interested.
Your inheritance is wrong, Toast is not a Recipe it has a Recipe. Ingredients of Recipe cannot be static because a Recipe can be used for toast, pancake or many other dishes.
More info on prototype can be found here: https://stackoverflow.com/a/16063711/1641941
If you want to inherit static members you need a better example: for example MyDate and MyDateTime.