-->

How & Why to use SUPER in code?

2019-05-25 21:27发布

问题:

I work with some advanced JavaScript people and they have used the SUPER keyword in their code. I admit, I don't have a good grasp of how and why one can and would use this.

Can someone direct me or show me how to become well versed in its usage and reasoning thereof?

Here are some examples:

openup: function( $super ) {
    $super();
    this.shop.enable_access();
}



addLeft: function( data ) {
    var cell = Element('td');
    if ( data.item_data ) {
        var item = new SRIL(data.item_data);
        item.attach(cell);
        item.show();
    }

    return cell;

}

var SRIL = Class.create(Module, {
initialize: function( $super, data ) {
    $super({ dom: 'show_line' });
    this.data = data;
    if ( data.Type[0] == 'Car' ) {
        //some code
    }
    else {
        // some code
    }
}

});

回答1:

JavaScript does not have such a thing.

Update: You should have a look at the documentation of the library that is in use here. This is a library feature, not a language one.



回答2:

Since Javascript doesn't have classical inheritance, structured instead according to a prototypal/functional model, developers have made various attempts at re-creating the classical model. super is part of one such strategy. The particular problem it solves is in the case of a child object that has the same method – even if it's just the constructor – as the parent object. Without creating super as an alias to the parent's methods, accessing such methods becomes somewhat cumbersome (and, in some cases, impossible).

John Resig has a wrapper that shows this off fairly well. Note his use of _super() in the first example to call the parent object's dance method.