如何在JavaScript中使用具有自我显示模块模式的链模式?

时间:2014-02-17 08:51:35

标签: javascript jquery html module-pattern

我有以下代码:

filtersManager = (function ($) {

    var that = this;

    function configure() {

        // some work

        return that;
    };

    function process() {

       // some work

        return that;
    }    

    return {
        // public functions
        configure: configure,
        process: process
    };
}(jQuery));

但是当使用下面的方法调用它时会失败:

filtersManager.configure().process();

Error: Object doesn't support property or method 'process'

而下面有效:

filtersManager.configure();
filtersManager.process();

4 个答案:

答案 0 :(得分:15)

你正在返回错误的东西(普通函数调用中的this是全局对象)。您想要返回最初创建的对象,我将其称为 interface

filtersManager = (function ($) {

    var interface = {
        // public functions
        configure: configure,
        process: process
    };

    function configure() {

        // some work

        return interface;
    };

    function process() {

       // some work

        return interface;
    }    

    return interface;
}(jQuery));

如果您想知道为什么我可以参考下面定义的功能,那就是由于吊装。

答案 1 :(得分:2)

立即函数在全局对象(window)上下文中执行。尝试类似的东西:

filtersManager = (function ($) {

    var that = {};

    that.configure = function() {
        // some work
        return that;
    };

    that.process = function() {
        // some work
        return that;
    }

    return that;

}(jQuery));


UPD。根据评论

构造函数模式似乎更符合您的需求:

var FiltersManager = (function($) {

    function FiltersManager() {}

    FiltersManager.prototype = {
        configure: function() {
            console.log('configure');
            return this;
        },
        process: function() {
            console.log('process');
            return this;
        }
    }

    return FiltersManager;

}(jQuery));

new FiltersManager().configure().process();

答案 2 :(得分:0)

至于继续别人所说的话,我认为你混淆了函数构造函数语法,它会起作用,类似于你所说的;

var G=function g()
{
  this.configure =function (){return this;}
  this.process  =function (){return this;}
};

var _= new G();




console.log(_.configure().process())

答案 3 :(得分:0)

如果你想在其他对象上重复使用这些功能,你也可以这样做



filtersManager = function ($) {

    function configure() {

        // some work

        return this;
    };

    function process() {

       // some work

        return this;
    }    

    return {
        // public functions
        configure: configure,
        process: process
    };
}(jQuery);




(OTOH,如果你想为它们创建别名,那么你必须将它们绑定到对象上)

或者,如果配置和处理很短,功能很简单:



filtersManager = (function ($) {

    return {
      
        // public functions
        configure: function () {

            // some work

            return this;
        },
      
        process: function () {

           // some work

            return this;
        }
    };
}(jQuery));