Javascript:函数作为参数,可能性
Javascript: functions as parameters, possibilities
我想知道是否可以在Javascript中做这样的事情:
one(plus(nine())); // returns 10
似乎是这样,但我不确定如何将one()的值传递给plus()函数。
这样的选择之一是定义(为简洁起见,使用箭头函数1):
// creates a function that either returns the number, or forwards the number
// as an argument to the provided function
// createNumber(10)() == 10
// createNumber(9)(Math.sqrt) == 3
var createNumber = value => f => f ? f(value) : value;
var one = createNumber(1);
var nine = createNumber(9);
// A very basic curryed implementation of addition
// plus(1)(2) == 3
var plus = a => b => a + b;
给出您所要求的
行为> one(plus(nine())
10
和一大堆同样被误导但正确的行为
> nine()
9
> nine(plus(one()))
10
> plus(nine())(one())
10
> nine(plus)(one())
10
1:参见Vincenzo Maggio对标准匿名函数的翻译
是的,Javascript是一种原型/函数式语言,可以创建新的函数并传递它们
//Returns a function that called without parameters extract the internal number
function number(num = null) {
return function(op) {
if (op == null) return num
else return op(num)
}
}
function plus(n1) {
return function(n2) {
return n2 + n1
}
}
var one = number(1)
var nine = number(9)
document.write(one(plus(nine())))
我保存了这把小提琴,如果你需要的话,可以随意演奏。
这绝对是可能的。
然而,你需要使用一些扭曲的逻辑,可能不太干净,你会有一个荒谬的困难,使它真正有用。
这个具体问题的一个可能的实际解决方案:
nine = function(c) {
if (typeof c === "object" && typeof c.method !== "undefined") {
return c.value + 9;
} else {
return 9;
}
};
plus = function(a) {
return {
value: a,
method: "+"
}
};
one = function(c) {
if (typeof c === "object" && typeof c.method !== "undefined") {
return c.value + 1;
} else {
return 1;
}
};
console.log( one( plus( nine() ) ) ) // -> 10
console.log( nine( plus( one() ) ) ) // -> 10
console.log( nine() ) // -> 9
console.log( one() ) // -> 1
JavaScript中的每个函数都是一个function对象。
在JavaScript中,函数是一等对象,因为它们可以像其他对象一样拥有属性和方法。它们与其他对象的区别在于函数可以被调用。
所以,就像对象可以从一个函数传递到另一个函数一样,你可以传递一个函数引用。
例如:function add(var a, var b){
return a+b;
}
function multiply(var a, var b){
return a*b;
}
var compute(var a, var b, var operation){
console.log(operation(a,b));
}
一旦您添加了冒号()
,该函数立即被调用,它不再是一个引用。如果碰巧赋值函数执行时的返回值,则赋值给LHS变量。
例如:var result = compute(10,20,add); // 20
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 使用Express捕获参数
- 参数变量出现ngTable指令问题
- AngularJS:我可以跳过函数参数回调吗
- 如何使用skip参数使用angular ui引导进行服务器端分页
- 要求未定义JS回调参数
- 我的jQuery插件参数没有正确启动,遇到了问题
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- jquery设置为使用参数运行
- Javascript”;类“;带有参数的扩展
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 函数未将值作为参数传递
- 如何将参数传递到angularJs中的工厂
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 正在传递JSONP标头's数据参数到另一个文件中的AJAX请求
- MVC 3页面导航和使用javascript传递参数
- 从查询字符串参数推断出正确的数据类型
- 传递包含'%的参数'在URL中
- Javascript:函数作为参数,可能性
- 表达要求.参数的可能性