我想做一个基于“”的示例代码。
我有如下代码。
define(["jquery","underscore", "backbone"], function($, _,Backbone) {
//Mixin :
//
/* Sometimes you have the same functionality for multiple objects
* and it doesn’t make sense to wrap your objects in a parent object.
* For example, if you have two views that share methods but don’t
* – and shouldn’t – have a shared parent view.
*/
//I can define an object that has attributes and methods that can be shared across different classes.
//This is called a mixin.
//Mixin Object
var C = Backbone.Model.extend({
c: function() {
console.log("We are different but have C-Method shared");
}
});
//To be Mixin-ed Object-1
var A = Backbone.Model.extend({
a: 'A',
});
//To be Mixin-ed Object-2
var B = Backbone.Model.extend({
b: 'B'
});
//underscore
_.extend(A.prototype, C);
_.extend(B.prototype, C);
return Backbone.Model.extend({
initialize: function(){
var testA = new A();
testA.c();
var testB = new B();
testA.c();
}
});
});如果我运行这段代码,就会出现一个错误:“testA.c不是函数”。从我研究过的一些示例代码来看,这应该是可行的。您能告诉我为什么这段代码不能尽可能详细地工作吗?
发布于 2016-06-15 02:34:41
您的问题是复制C的属性而不是C.prototype的属性(方法c实际上是在这里定义的)。只需改变:
_.extend(A.prototype, C);
_.extend(B.prototype, C);至:
_.extend(A.prototype, C.prototype);
_.extend(B.prototype, C.prototype);一切都会如愿以偿。
https://stackoverflow.com/questions/37825006
复制相似问题