Using John Resig's “simple JavaScript inheritance” how can I call a super method PLUS extra code from within a method?

StackOverflow https://stackoverflow.com/questions/9145056

Question

I decided to try out JavaScript genius John Resig's "simple JavaScript inheritance" as detailed on this blog page:

http://ejohn.org/blog/simple-javascript-inheritance/

I'm curious how one might override a method with code that calls the super method. In other words, let's say I start with a Person class:

var Person = Class.extend({
    init: function ( name, age ) {
        this.name = name;
        this.age = age;
    }
});

I extend that Person class to create a new class Worker:

var Worker = Person.extend({
    init: function ( name, age, occupation ) {
        this.name = name;
        this.age = age;
        this.occupation = occupation;
    }
});

There's repetition of code in the two versions of the init method. The following two lines are executed no matter which class I'm using:

this.name = name;
this.age = age;

It seems like I should be able to call the Person class's init method from within the Hero class's init method and then throw in the extra line of code with the occupation property.

I can't do that with Mr. Resig's code, though. The following doesn't work:

var Worker = Person.extend({
    init: function ( name, age, occupation ) {
        this._super(arguments);
        this.occupation = occupation;
    }
});

As soon as the extend method called from Person to create the Worker class sees *this._super(arguments)* it replaces the entirety of Worker's init with Person's init leaving me with an undefined occupation property.

Does anyone have any suggestions as to how to get around this without having to modify Mr. Resig's code? I'm currently trying out different ways to implement the concept of a "super," but the fact that I can't get this to work with the existing code is stuck in my head. :-)

UPDATE: I realized that I made one small error in implementing Mr. Resig's code which is why this behaved the way I described. @chuckj correctly pointed out an error in Worker's init, too.

Was it helpful?

Solution

Change the Worker definition to,

var Worker = Person.extend({ 
    init: function (name, age, occupation) { 
        this._super(name, age); 
        this.occupation = occupation; 
    } 
}); 

you don't pass the arguments array, you call the _super with the parameters it expects.

OTHER TIPS

It seems your goal is to proxy the arguments to this._super. In this case you can just apply() them :

var Worker = Person.extend({
    init: function ( name, age, occupation ) {
        this._super.apply(this, arguments);
        this.occupation = occupation;
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top