Access member of parent class with javascript inheritance?

I need to extend a base class with additional features in javascript. I use backbone.js inheritance as an example here, but this is a general question about extending classes.

http://addyosmani.github.com/backbone-fundamentals/#inheritance-mixins

Parent = Backbone.View.extend({ value: "Parent value", func: function(){ alert('Parent function, ' + this.value); } }); Child = Parent.extend({ value: "Child value", func: function(){ alert('Child function, ' + this.value); }, test: function(){ this.constructor.__super__.func.call(this); //Parent.prototype.func.call(this) } }); var child = new Child(); child.test(); // prints: Parent function, Child value // should print: Parent function, Parent value 

Below is a jsfiddle sandbox to facilitate experimentation.

The problem is that the extend () function seems to be more like implementing an interface instead of inheriting. So the child is really still parental, but with additional member functions. The value element appears to be virtual, so there is only one instance, not one per child. In C ++, I could say Parent :: func () and inside, this-> value will be "Parent value".

I tried various ._super extensions for backbone.js, but they still suffer from the "this" wrong context in Parent. I also tried _.bindAll () in both / both of the child / parent, but with an error for the same reason:

 initialize: function() { _.bindAll(this, 'func'); } 
  • What is the cleanest way to have β€œthis” be the appropriate context in the parent block in javascript, or at least mimic this functionality with minimal code?

  • Do I need to create a β€œparent” element in Child and create it to create β€œvalues” for each child?

0
source share

All Articles