标签:style blog io os 使用 java ar strong for
1. 函数的“应用”(Function Application)
// define a function var sayHi = function (who) { return "Hello" + (who ? ", " + who : "") + "!"; }; // invoke a function sayHi(); // "Hello" sayHi(‘world‘); // "Hello, world!" // apply a function sayHi.apply(null, ["hello"]); // "Hello, hello!"
var alien = { sayHi: function (who) { return "Hello" + (who ? ", " + who : "") + "!"; } }; alien.sayHi(‘world‘); // "Hello, world!" sayHi.apply(alien, ["humans"]); // "Hello, humans!"
// the second is more efficient, saves an array sayHi.apply(alien, ["humans"]); // "Hello, humans!" sayHi.call(alien, "humans"); // "Hello, humans!"
// for illustration purposes // not valid JavaScript // we have this function function add(x, y) { return x + y; } // and we know the arguments add(5, 4); // step 1 -- substitute one argument function add(5, y) { return 5 + y; } // step 2 -- substitute the other argument function add(5, 4) { return 5 + 4; } 上面代码里的step1和step2不合法。但由于函数的执行过程就是它的应用过程,我们如果可以编程实现这一机制,比如这样: var add = function (x, y) { return x + y; }; // full application add.apply(null, [5, 4]); // 9 // partial application var newadd = add.partialApply(null, [5]); // applying an argument to the new function newadd.apply(null, [4]); // 9
// a curried add() // accepts partial list of arguments function add(x, y) { var oldx = x, oldy = y; if (typeof oldy === "undefined") { // partial return function (newy) { return oldx + newy; }; } // full application return x + y; } // test typeof add(5); // "function" add(3)(4); // 7 // create and store a new function var add2000 = add(2000); add2000(10); // 2010
// a curried add // accepts partial list of arguments function add(x, y) { if (typeof y === "undefined") { // partial return function (y) { return x + y; }; } // full application return x + y; }
function schonfinkelize(fn) { var slice = Array.prototype.slice, stored_args = slice.call(arguments, 1); return function () { var new_args = slice.call(arguments), args = stored_args.concat(new_args); return fn.apply(null, args); }; }
// a normal function function add(x, y) { return x + y; } // curry a function to get a new function var newadd = schonfinkelize(add, 5); newadd(4); // 9 // another option -- call the new function directly schonfinkelize(add, 6)(7); // 13 也可多次执行schonfinkelize,让函数多次分步执行: // a normal function function add(a, b, c, d, e) { return a + b + c + d + e; } // works with any number of arguments schonfinkelize(add, 1, 2, 3)(5, 5); // 16 // two-step currying var addOne = schonfinkelize(add, 1); addOne(10, 10, 10, 10); // 41 var addSix = schonfinkelize(addOne, 2, 3); addSix(5, 5); // 16
标签:style blog io os 使用 java ar strong for
原文地址:http://www.cnblogs.com/Bryran/p/3976131.html