我需要从继承的 MyModel
类内部调用父类的 initialize
方法,而不是像今天这样完全覆盖它。
我怎么能这样做?
这是我的代码现在的样子:
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.
},
});
尝试
MyModel = BaseModel.extend({
initialize: function() {
BaseModel.prototype.initialize.apply(this, arguments);
// Continue doing specific stuff for this child-class.
},
});
MyModel = BaseModel.extend({
initialize: function() {
MyModel.__super__.initialize.apply(this, arguments);
// Continue doing specific stuff for this child-class.
},
});
this.__super__.initialize.apply(this, arguments);
__ super __
并不打算直接使用它。
BaseModel.prototype.initialize.apply(this, arguments);
?这应该在没有 __super__
的情况下工作。
__super__
不打算直接使用。
当我试图在我的模型中继承时,这对我有用:
MyModel.prototype.initialize.call(this, options);
引用自 http://documentcloud.github.com/backbone/#Model-extend
谢谢。
我想会是
MyModel = BaseModel.extend({
initialize: function() {
this.constructor.__super__.initialize.call(this);
// Continue doing specific stuff for this child-class.
},
});
this.__super__.initialize.call(this);
this.__super__.prototype.initialize.call(this);
和 this.__super__.initialize.call(this);
在 Firebug 中都会引发 this.__super__ is undefined
。
__super__
不打算直接使用。
类似于@wheresrhys,但如果 BaseModel.initialize 需要参数,我会使用 apply 而不是 call。我尽量避免处理可以在初始化时传递给主干模型的属性映射,但如果 BaseModel 实际上是视图或集合,那么我可能想要设置选项。
var MyModel = BaseModel.extend({
initialize: function() {
this.constructor.__super__.initialize.apply(this, arguments);
// Continue doing specific stuff for this child-class.
},
});
__super__
不打算直接使用。
这是一个多代 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;
}
您可能会考虑使用功能继承重写您的代码。
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
};
};
不定期副业成功案例分享
_.bindAll(this)
调用,这似乎也可以工作,这会使构造函数的__super__
属性未定义。__super__
更好有下划线表示私人成员