English 中文(简体)
Java 旧式方法链条挑战
原标题:JavaScript method chaining challenge
  • 时间:2009-09-18 17:03:28
  •  标签:

(这一问题实际上并不仅限于语言,因此,请能够自由地以其他语文提出解决办法。)

我很想知道,能否在 Java文中写出这样的东西:

// 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

最佳回答

你可以轻而易举地写:

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

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

如果你想去做,我建议你读一下,currying部分功能申请

问题回答

另一种版本,没有结束:

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);

链条用于在一个物体上采用多种方法。 因此,你会把这一职能视为目标,并在此规定时间:

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

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

我刚刚写了little helper,以某种一致的方式制作类似内容的节目。

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

想法是,你通过指定起入职功能,建造一个具有一定初始状态的流层建筑商。 然后,每条电线向新国家过渡。

你从接连一队电话中获得的价值可以发挥功能,这就要求从这个国家中找到价值,以及你通过的任何选择。

  • entry : * ⟶ S
  • transition : (S ⟶ *) ⟶ S
  • exit : 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 */}
});

So 0, 1 are entry, exit functions. All other functions transition an internal state. All functions can take arguments, eg. opt

我们树立了我们新拟定的亚特兰大的榜样,

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

并称之为

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

查阅https://github.com/0x01/mu-ffsm/blob/master/%C2%B5-ffsm.js”rel=“nofollow”>,以了解如何执行。

页: 1 利用这一答案更新:D





相关问题
热门标签