Javascript模式:调用多个方法

javascript pattern: calling multiple method

本文关键字:方法 调用 模式 Javascript      更新时间:2023-09-26

我在谷歌上搜索过,并阅读了许多关于js模式的文章,我很困惑。我在stackoverflow上搜索,仍然很困惑。所以,我想我必须在这里问一下。(我还是个javascript新手)

我想"创建模块、单例或其他模式,然后同时滚动/调用多个方法"。

示例:Yourlib.getId('elmID').setColor('somecolor').setHtml('somehtml').show().blaa.blaa.blaa

如何创建基本模式?

var Yourlib = (function() {
    var anyPrivateVar = blablabla;
    anyFunctions(){
        any stuff...
    }
    return {
        setHtml: blablabla,
        method2: function() {
            anything... 
        }
        getId: function() {
            anything...
        },
        setColor: function() {
            anything...
        },
        show: function() {
            anything...
        }
    }
}())

如何创建模式,所以我可以调用/滚动方法在同一时间?Yourlib.getId('elmID').setColor('somecolor').setHtml('somehtml').show().blaa.blaa.blaa

此模式有时被称为" chainaining ",或者,当用于最终将构造其他类的选项类时,称为"builder"模式。

基本上,这样做的方法是让每个函数返回一个对象,该对象可以调用后续方法(通常该对象与当前方法调用的对象相同)。

在JavaScript中,你可以这样做:

 var Point = function(x, y) {
   this.x = x;
   this.y = y;
 };
 var PointBuilder = function() {
   this.x = null;
   this.y = null;
 };
 PointBuilder.prototype.setX = function(x) {
   this.x = x; 
   return this;  // <= so that one can call .setY() on the result
 };
 PointBuilder.prototype.setY = function(y) {
   this.y = y; 
   return this;  // <= so that one can call .setX() on the result
 };
 PointBuilder.prototype.build = function() {
   return new Point(this.x, this.y);
 };

上面的代码是一个简单的例子,但是您可以理解其中的意思。基本上,从你的方法中返回this或返回其他提供剩余可用方法的对象。

我想你是在要求链接方法。这里有一个简单的例子。关键是return对象返回。

var obj = {  
    method1: function() { alert('first');   return obj; },
    method2: function() { alert('second');  return obj; },
    method3: function() { alert('third');   return obj; },
    method4: function() { alert('fourth');  return obj; }
}
obj.method1().method2().method3().method4(); 

现场演示

这被称为方法链接,在jQuery中大量使用。您只需在您希望能够链接的方法中返回当前上下文:

show: function() {
    // allow chaining
    return this;
}

你也应该看看"fluent" api。我个人不太看重流畅的api,但人们确实喜欢他们的阅读方式,尤其是在编写测试时。

链接也是一种"延迟"实际计算的好方法(一种延迟计算)-参见underscore的_.chain()方法与它的value()方法[我不认为underscore实际上做了什么太花哨的事情]