在Javascript骨干类中调用超级方法

时间:2013-08-12 16:52:59

标签: javascript backbone.js

我有一个扩展Backbone.View的基类。我想在覆盖子类的'initialize'之后能够调用super的'initialize'。如何以最强大和最清晰的方式完成在javascript中调用扩展类的超级?

我已经看过这个(Super in Backbone),有没有更明确的方法来实现这个目标,而不必知道超级班的人是谁?

App.Views.BaseView = Backbone.View.extend({
    initialize: function(templateContext){
        this.super_called = true;
    }
});

对于我的所有子视图,我想利用已经编写的初始化函数。

App.Views.ChildViewWorks = App.Views.extend({});
var newView = new App.Views.ChildViewWorks();
alert(newView.super_called); // print true

App.Views.ChildViewDoesNotWork = App.Views.extend({
    initialize: function(templateContext){
        this.super_called = false;
        //what line of code can I add here to call the super initialize()?
    }   
});
var newViewWrong = new App.Views.ChildViewDoesNotWork();
alert(newViewWrong.super_called); //now equal to false because I have not called the super.

1 个答案:

答案 0 :(得分:2)

App.Views.ChildViewDoesNotWork = App.Views.BaseView.extend({
    initialize: function(templateContext){
        this.super_called = false;
        App.Views.BaseView.prototype.initialize.call(this);
    }   
});