Mixin Pattern使用下划线,_. extend关键字

时间:2016-06-15 02:14:48

标签: javascript design-patterns backbone.js mixins

我想根据' Mixin Pattern'。

制作示例代码

我有一个如下代码。

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不是函数'。 根据我研究的一些示例代码判断,这应该有效。 您能告诉我这段代码尽可能不详细的原因吗?

1 个答案:

答案 0 :(得分:2)

您的问题是您复制了C的属性而不是C.prototype的属性(这是实际定义方法c的位置)。只需更改:

_.extend(A.prototype, C);
_.extend(B.prototype, C);

为:

_.extend(A.prototype, C.prototype);
_.extend(B.prototype, C.prototype);

一切都会按预期工作。