【问题标题】:Mixin Pattern using underscore, _.extend keyword使用下划线、_.extend 关键字的 Mixin 模式
【发布时间】:2016-06-15 02:14:48
【问题描述】:

我想制作一个基于“混合模式”的示例代码。

我有如下代码。

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 不是函数”。 从我研究的一些示例代码来看,这应该有效。 您能否尽可能详细地告诉我此代码无法正常工作的原因?

【问题讨论】:

  • 您定义了_c 属性,但您调用了c (testA.c())。我认为它们应该是一样的。
  • 我改变了它......但它在同样的错误下不起作用。我认为还有另一个原因。

标签: javascript design-patterns backbone.js mixins


【解决方案1】:

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

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

到:

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

一切都会按预期进行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多