Javascript Inherit Static And Instance Methods/properties
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, a
Solution 1:
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.
functionRecipe(name,ingredients) {
this.name=name;
this.ingredients = ingredients;
};
varToast = function(){}
Toast.prototype.recipe = newRecipe('toast',{
bread: '2 slices',
butter: '1 knob',
jam: '1 tablespoon'
});
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.
varMyDate=function(dateString){
this.date=(dateString)?newDate(dateString)
:newDate();
};
MyDate.YEAR=Date.prototype.getFullYear;
//... others like MONTH, DAY ...MyDate.prototype.get = function(what){
if(what && typeof what==='function'){
return what.call(this.date);
}
console.log('nope');
};
varMyDateTime=function(dateString){
MyDate.call(this,dateString);
};
//set static properties (can write a function for this)for(mystatic inMyDate){
if(MyDate.hasOwnProperty(mystatic)){
MyDateTime[mystatic]=MyDate[mystatic];
}
}
MyDateTime.HOUR=Date.prototype.getHours;
//instead of breaking encapsulation for inheritance// maybe just use Object.create and polyfil if needed// and stop reading DC when it comes to this subjectMyDateTime.prototype=Object.create(MyDate.prototype);
MyDateTime.prototype.constructor=MyDateTime;
var d = newMyDate();
console.log(d.get(MyDate.YEAR));
var dt = newMyDateTime();
console.log(dt.get(MyDateTime.YEAR));
console.log(dt.get(MyDateTime.HOUR));
Solution 2:
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.
varBase = new ds.class({
type: 'Base',
constructor: function() {
this.instanceprop: 'am i instance?'
},
staticprop: 'am i static?'
});
varExample = new ds.class({
type: 'Example',
inherits: Base,
constructor: function() {}
});
var eb = newBase();
var ex = newExample();
console.log( Base.staticprop );
console.log( eb.instanceprop );
console.log( Example.staticprop );
console.log( ex.instanceprop );
Post a Comment for "Javascript Inherit Static And Instance Methods/properties"