【问题标题】:Method chaining within namespace命名空间内的方法链
【发布时间】:2016-06-07 11:01:35
【问题描述】:

我不知道如何在同一个命名空间中链接方法(我不想创建一个类,而是直接调用它):

var namespace = {
    one: function(args) {
        // do something
    },
    two: function() {
        // do something in addition
    }
}

// call both
namespace.one(true).two();

【问题讨论】:

  • return this 可以在您的示例中使用。

标签: javascript namespaces method-chaining


【解决方案1】:

您需要返回namespacethis

var namespace = {
    one: function(args) {
        // do something
        console.log('one');
        return this;
    },
    two: function() {
        // do something in addition
        console.log('two');
        return this;
    }
}

// call both
namespace.one(true).two();

【讨论】:

    【解决方案2】:

    您需要返回对命名空间对象的引用以链接它。

    var namespace = {
        one: function (args) {
           // Do something
           return this;
        },
        two: function () {
           // Do something
           return this;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-10
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多