JavaScript方法链接挑战

时间:2009-09-18 17:03:28

标签: javascript method-chaining

(这个问题并不仅限于语言,所以请随意提交其他语言的解决方案。)

我只是想知道是否可以在JavaScript中编写类似的内容:

// Wait 3 seconds and then say our message in an alert box
wait(3).then(function(){alert("Hello World!");});

传统方式是写

// Wait 3 seconds and then say our message in an alert box
setTimeout(function(){alert("Hello World!");}, 3000);

很抱歉,如果这是一个菜鸟问题:p

5 个答案:

答案 0 :(得分:37)

您可以轻松编写:

function wait(delay) {
  return {
    then: function (callback) {
      setTimeout(callback, delay*1000);
    }
  };
}

wait(3).then(function(){alert("Hello World!");});

如果您想深入了解,我建议您阅读curryingpartial function application,这些主题非常有趣。

答案 1 :(得分:14)

又一个版本,没有关闭:

function wait(seconds) {
    if(this instanceof wait)
        this.delay = seconds;
    else return new wait(seconds);
}

wait.prototype.then = function(callback) {
    setTimeout(callback, this.delay * 1000);
};

使用更多代码,您甚至可以重复调用函数:

function wait(seconds) {
    if(this instanceof wait)
        this.delay = seconds;
    else return new wait(seconds);
}

wait.prototype.then = function(callback) {
    setTimeout(callback, this.delay * 1000);
    return this;
};

wait.prototype.wait = function(seconds) {
    this.delay += seconds;
    return this;
};

var start = new Date;
function alertTimeDiff() {
    alert((new Date - start)/1000);
}

wait(1).then(alertTimeDiff).wait(3).then(alertTimeDiff);

答案 2 :(得分:2)

链接用于在一个对象上执行多个方法。因此,您宁愿将该函数视为对象并在那里设置超时:

Function.prototype.callAfter = function(delay) {
    setTimeout(this, delay*1000);
};

(function(){alert("Hello World!");}).callAfter(3);

答案 3 :(得分:0)

如果你做OO Javascript,那么是的,你可以进行方法链接。

一些流行的JavaScript框架可以做到这一点。 jQuery通过为通常不返回值的函数返回jQuery对象来完成此任务。

答案 4 :(得分:0)

我刚写了一个little helper以一种有点一致的方式创建这样的API,也许你喜欢它。

// > npm i mu-ffsm # install node dependency
var mkChained = require('mu-ffsm');

这个想法是你通过调用一个入口函数来构造一个具有类型S的初始状态的流畅构建器。然后每个链接调用将状态转换为新状态。

链接一堆调用所得到的值可以作为一个函数执行,它调用exit来从该状态构造一个值以及传入的任何选项。

  • 条目:*⟶S
  • 过渡:(S⟶*)⟶S
  • 退出:S⟶(*⟶*)

例如

var API = mkChained({
  0:    function(opt)    {return ;/* create initial state */},
  then: function(s, opt) {return s; /* new state */},
  whut: function(s, opt) {return s; /* new state */},
  1:    function(s, opt) {return ;/* compute final value */}
});

所以01是入口,退出函数。所有其他功能都转换为内部状态。 所有函数都可以使用参数,例如。 opt

我们创建了新制作的API的实例

var call = API() // entry
   .whut()       // transition
   .then()       // transition
   .whut();      // transition

并称之为

var result0 = call() // exit
  , result1 = call() // exit

查看(小)source以了解如何实施。

PS。使用此答案更新文档:D