JavaScript方法链接的挑战
-
22-07-2019 - |
题
(这个问题不是真的局限于语言因此,请随时提出解决方案中的其他语言了。)
我只是想知道是否有可能编写这样的东西在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
其他提示
又一版本,而不闭合:
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);
如果你这样做OO的Javascript,那么,你可以做方法链接。
一些流行的JavaScript框架的做到这一点。 jQuery的通过返回jQuery对象为通常不会返回值的函数来实现的。
我刚刚写了一个 小帮手 以某种一致的方式创建这样的 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 */}
});
所以 0
, 1
分别是入口、出口函数。所有其他函数都会转换内部状态。所有函数都可以带参数,例如。 opt
我们创建一个新设计的 API 实例,
var call = API() // entry
.whut() // transition
.then() // transition
.whut(); // transition
并称之为
var result0 = call() // exit
, result1 = call() // exit
看看(小) 来源 看看这是如何实现的。
附:使用这个答案来更新文档:D
不隶属于 StackOverflow