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);
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?
source share