使用下划线,_.extend 关键字的混合模式

Mixin Pattern using underscore, _.extend keyword

我想根据'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 is not a function'。 从我研究的一些示例代码来看,这应该有效。 能否请您尽可能详细地告诉我这段代码不起作用的原因?

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

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

至:

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

一切都会按预期进行。