JavaScript方法链接挑战

kiz*_*zx2 8 javascript method-chaining

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

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

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

传统的方式是写作

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

对不起,如果这是一个菜鸟问题:p

CMS*_*CMS 37

你可以轻松地写它:

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

wait(3).then(function(){alert("Hello World!");});
Run Code Online (Sandbox Code Playgroud)

如果您想深入了解,我建议您阅读有关currying部分功能应用的内容,这些主题非常有趣.


Chr*_*oph 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);
};
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)