0

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

5
  • Why would a Child method want to set a property on the Base.staticProp object to 'child'? Commented Aug 11, 2014 at 23:17
  • @Bergi see my updated demo. I define a recipe base class for other recipes, i.e. Toast, Spaghetti, etc. What probably confused you was the fact that I wanted every subclass to get its own static property. Commented Aug 11, 2014 at 23:41
  • Uh, I think toast should be an instance of Recipe? The ingredients quite certainly don't qualify as a static property. Commented Aug 11, 2014 at 23:44
  • @Bergi Let's just say in this case Toast is the basis of all toast so it needs to be a class (it is a model). Other kinds of toast would extend from Toast. Commented Aug 11, 2014 at 23:49
  • Hm, but then they still wouldn't share the .ingredients. Also, Recipe could become a meta-class to produce models, which is a bit complex. Commented Aug 11, 2014 at 23:57

2 Answers 2

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.

function Recipe(name,ingredients) {
  this.name=name;
  this.ingredients = ingredients;
};

var Toast = function(){}
Toast.prototype.recipe = new Recipe('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.

var MyDate=function(dateString){
  this.date=(dateString)?new Date(dateString)
    :new Date();
};
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');
};

var MyDateTime=function(dateString){
  MyDate.call(this,dateString);
};
//set static properties (can write a function for this)
for(mystatic in MyDate){
  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 subject
MyDateTime.prototype=Object.create(MyDate.prototype);
MyDateTime.prototype.constructor=MyDateTime;

var d = new MyDate();
console.log(d.get(MyDate.YEAR));
var dt = new MyDateTime();
console.log(dt.get(MyDateTime.YEAR));
console.log(dt.get(MyDateTime.HOUR));
Sign up to request clarification or add additional context in comments.

Comments

0

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.

var Base = new ds.class({
    type: 'Base',
    constructor: function() {
        this.instanceprop: 'am i instance?'
    },
    staticprop: 'am i static?'
});

var Example = new ds.class({
    type: 'Example',
    inherits: Base,
    constructor: function() {}
});

var eb = new Base();
var ex = new Example();

console.log( Base.staticprop );
console.log( eb.instanceprop );
console.log( Example.staticprop );
console.log( ex.instanceprop );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.