CanJS - Plugins - super

canjs
canjs-plugins

What is the purpose of the super plugin?

can.Construct.super is a plugin that makes it easier to call base functions from inside inheriting functions. With this plugin, functions that are inheriting from base functions are provided with a specialized this._super reference to the base function from which they inherit. This is especially useful for calling base classes' init and setup, but it can be used in any inheriting function.

Without using super:

var Person = can.Construct.extend({
    init: function(first, last) {
        this.first = first;
        this.last  = last;
    }
});

var Programmer = Person.extend({
    init: function(first, last, language) {
        // call base's init
        Person.prototype.init.apply(this, arguments);
        // other initialization code
        this.language = language;
    },
    bio: function() {
        return "Hi! I'm " + this.first + " " + this.last +
            " and I write " + this.language + ".";
    }
});

With using super:

var Person = can.Construct.extend({
    init: function(first, last) {
        this.first = first;
        this.last  = last;
    }
});

var Programmer = Person.extend({
    init: function(first, last, language) {
        // call base's init
        this._super(first, last);
        // other initialization code
        this.language = language;
    },
    bio: function() {
        return "Hi! I'm " + this.first + " " + this.last +
            " and I write " + this.language + ".";
    }
});

How can we pass an array of arguments to _super?

If you want to pass an array of arguments (or an arguments object) to _super, use apply:

var Programmer = Person.extend({
    init: function(first, last, language) {
        // call base's init
        this._super.apply(this, arguments);
        // other initialization code
        this.language = language;
    },
    bio: function() {
        return "Hi! I'm " + this.first + " " + this.last +
            " and I write " + this.language + ".";
    }
});
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License