在Backbone中访问父类

时间:2012-01-23 11:04:43

标签: javascript oop class inheritance backbone.js

我需要从继承的initialize - 类中调用父类的MyModel方法,而不是像我今天那样完全覆盖它。

我怎么能这样做?

以下是我的代码现在的样子:

BaseModel = Backbone.Model.extend({
    initialize: function(attributes, options) {
        // Do parent stuff stuff
    }
});

MyModel = BaseModel.extend({
    initialize: function() {
        // Invoke BaseModel.initialize();
        // Continue doing specific stuff for this child-class.
    },
});

8 个答案:

答案 0 :(得分:127)

尝试

MyModel = BaseModel.extend({
    initialize: function() {
        BaseModel.prototype.initialize.apply(this, arguments);
        // Continue doing specific stuff for this child-class.
    },
});

答案 1 :(得分:50)

MyModel = BaseModel.extend({
    initialize: function() {
        MyModel.__super__.initialize.apply(this, arguments);
        // Continue doing specific stuff for this child-class.
    },
});

答案 2 :(得分:11)

当我试图在我的模型中继承时,这对我有用:

MyModel.prototype.initialize.call(this, options);

引自http://documentcloud.github.com/backbone/#Model-extend

感谢。

答案 3 :(得分:5)

我认为这是

MyModel = BaseModel.extend({
    initialize: function() {
        this.constructor.__super__.initialize.call(this);
        // Continue doing specific stuff for this child-class.
    },
});

答案 4 :(得分:4)

这似乎几乎与Super in Backbone重复,所以你想要这样的东西:

Backbone.Model.prototype.initialize.call(this);

答案 5 :(得分:2)

与@wheresrhys类似,但我会使用apply而不是call,以防BaseModel.initialize需要参数。我尝试避免处理可在初始化时传递给Backbone模型的属性映射,但如果BaseModel实际上是View或Collection,那么我可能想要设置选项。

var MyModel = BaseModel.extend({
    initialize: function() {
        this.constructor.__super__.initialize.apply(this, arguments);
        // Continue doing specific stuff for this child-class.
    },
});

答案 6 :(得分:0)

这是一个多代callSuper方法,只需将其添加到扩展类中即可。

callSuper: function (methodName) {
    var previousSuperPrototype, fn, ret;

    if (this.currentSuperPrototype) {
        previousSuperPrototype = this.currentSuperPrototype;
        // Up we go
        this.currentSuperPrototype = this.currentSuperPrototype.constructor.__super__;
    } else {
        // First level, just to to the parent
        this.currentSuperPrototype = this.constructor.__super__;
        previousSuperPrototype = null;
    }

    fn = this.currentSuperPrototype[methodName];

    ret = (arguments.length > 1) ? fn.apply(this, Array.prototype.slice.call(arguments, 1)) : fn.call(this);

    this.currentSuperPrototype = previousSuperPrototype;

    return ret;
}

答案 7 :(得分:-4)

您可以考虑使用功能继承来重写代码。

var BackBone=function(){
    var that={};

    that.m1=function(){

   };
   return that;

};

var MyModel=function(){

 var that=BackBone();
 var original_m1=that.m1;

//overriding of m1
 that.m1=function(){
    //call original m1
 original_m1();
 //custom code for m1
  };
};