Javascript函数调用类似于somefunction(“Hi”)(“Hello”))(“How”)
Javascript function call like somefunction("Hi")("Hello")("How")
请看一下这段代码。我需要用这个代码显示一条警告信息"mikäon elämän tarkoitus?"
window["mikä"]("on")("elämän")("tarkoitus")("?");
我需要编写一个函数或一段代码,当我执行该代码时,它将显示警报消息。
我写了一个这样的函数:
window["mikä"] = function(str){
alert(str);
}
当我调用窗口"mikä"时,这是有效的,但如果我在控制台中添加更多类似下面的内容,我会看到一个类型错误。
window["mikä"]("on")("Hello")("How");
我的问题是,像下面这样调用是否有效,因为有多个函数符号?
window["mikä"]("on")("elämän")("tarkoitus")("?")
要实现您正在寻找的功能,一种方法是编写一个返回函数的函数,该函数返回前面提到的其他函数。如果函数的数量是已知的,那就可以了。另一种方法是使用一种称为currying的函数式编程技术,即
将对一个包含多个参数(或一个参数元组)的函数的求值转换为对一系列函数的求值的技术,每个函数都有一个参数(部分应用程序)。
你可以这样写你自己的咖喱函数:
function curry(func, args_) {
var self = this;
self.args = args_ || [];
return function() {
var extended_args = [].concat(self.args).concat(Array.slice(arguments));
if(extended_args.length >= func.length)
return func.apply(this, extended_args);
return new curry(func, extended_args);
};
}
var funcName = "mikä";
window[funcName] = curry(functionstr1, str2, str3, str4) {
alert(funcName + ' ' + str1 + ' ' + str2 + ' ' + str3 + str4);
});
window["mikä"]("on")("elämän")("tarkoitus")("?");
如果你有兴趣学习更多关于JS中的currying/functional编程的知识,这里有一些资源可以帮助你。
http://kukuruku.co/hub/javascript/an-interesting-task-for-an-interview-currying-and-partial-applicationof-a-functionhttp://tech.pro/tutorial/2011/functional-javascript-part-4-function-curryingReginald Braithwaite在NDC奥斯陆的演讲
您希望返回值也是一个函数,这样对返回值的其他调用将调用相同的函数。只需添加此
window["mikä"] = function(str){
alert(str);
return window["mikä"];
}
编辑:误解了你的问题,这将产生多条警告信息。很抱歉
您可能想要嵌套函数调用
window["mikä"] = function(s1){
return function(s2) {
return function(s3) {
alert(s1 + ' ' + s2 + ' ' + s3);
}
}
}
window["mikä"]("on")("elämän")("tarkoitus")("?");
至于在函数中获取函数名,确实没有什么好方法,应该避免。
- 节点Js:How to catch a“;没有这样的文件或目录“;读取线模块出错
- how to convert html <div> to pdf
- how to split a string with ','
- How to declare a Map containing certain properties with flow
- How to apply javascript on <asp:Buttonfield>?
- How to target an h1 inside an <a>?
- 谷歌图表-“;快速入门Hello World;不在IE8中渲染
- How to “emitter.setMaxListeners()”?
- How can I get and replace this in javascript ( jquery?
- How to replace space with " "
- Javascript:如何对属性变量(例如var.hello.push)执行数组方法?太习惯AS3了
- vue-router:how to not `saveScrollPosition`
- jquery ajax post to .aspx page load - how to read variable p
- 如何下载杜兰达尔示例项目(Hello World)的源代码
- 使用hello.js自定义OAuth2提供程序
- 为什么可以't〃;decodeURIComponent”;或“;decodeURI”;解码”;hello+wor
- 我希望这个img类是一个按钮,当你点击它时,它会播放hello.mp3
- 用我的名字创建一个变量.然后提醒字符串“hello-from”加上我创建的变量
- 用Angularjs返回两个承诺,How To Chain So UI有$scope
- Javascript函数调用类似于somefunction(“Hi”)(“Hello”))(“How”)