Function Application

apply() takes two parameters: the first one is an object to bind to this inside of the function, the second is an array or arguments, which then becomes the array-like arguments object available inside the function. If the first parameter is null, then this points to the global object, which is exactly what happens when you call a function that is not a method of a specific object.

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

In the preceding snippet,  this inside of  sayHi() points to  alien. In the previous example this points to the global object.

When you have a function that takes only one parameter, you can save the work of creating arrays with just one element:

// the second is more efficient, saves an array

sayHi.apply(alien, ["humans"]); // "Hello, humans!"

sayHi.call(alien, "humans"); // "Hello, humans!"

Partial Application

var add = function(x, y) {

    return x + y;

};

// full application

add.apply(null, [5, 4]);
// // partial application var newadd = add.partialApply(null, [5]); // applying an argument to the new function newadd.apply(null, [4]);
//

Here’s no  partialApply() method and functions in JavaScript don’t behave like this by default. But you can make them, because JavaScript is dynamic enough to allow this. The process of making a function understand and handle partial application is called currying.

// 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);
// // create and store a new function var add2000 = add(2000); add2000(10);
//

General-purpose currying function

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);
// // another option -- call the new function directly schonfinkelize(add, 6)(7);
// // 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);
// // two-step currying var addOne = schonfinkelize(add, 1); addOne(10, 10, 10, 10);
// var addSix = schonfinkelize(addOne, 2, 3); addSix(5, 5);
//

When to Use Currying

When you find yourself calling the same function and passing mostly the same parameters, then the function is probably a good candidate for currying. You can create a new function dynamically by partially applying a set of arguments to your function. The new function will keep the repeated parameters stored (so you don’t have to pass them every time) and will use them to pre-fill the full list of arguments that the original function expects.

References: 

JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

JavaScript Patterns 4.10 Curry的更多相关文章

  1. JavaScript Patterns 2.10 Naming Conventions

    1. Capitalizing Constructors var adam = new Person(); 2. Separating Words camel case - type the word ...

  2. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

  3. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  4. JavaScript Patterns 6.6 Mix-ins

    Loop through arguments and copy every property of every object passed to the function. And the resul ...

  5. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  6. JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...

  7. JavaScript Patterns 6.3 Klass

    Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...

  8. JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance

    // the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...

  9. JavaScript Patterns 6.1 Classical Versus Modern Inheritance Patterns

    In Java you could do something like: Person adam = new Person(); In JavaScript you would do: var ada ...

随机推荐

  1. Web.config配置文件详解

    整理了一下ASP.NET Web.config配置文件的基本使用方法.很适合新手参看,由于Web.config在使用很灵活,可以自定义一些节点.所以这里只介绍一些比较常用的节点. <?xml v ...

  2. 不可或缺 Windows Native (18) - C++: this 指针, 对象数组, 对象和指针, const 对象, const 指针和指向 const 对象的指针, const 对象的引用

    [源码下载] 不可或缺 Windows Native (18) - C++: this 指针, 对象数组, 对象和指针, const 对象,  const 指针和指向 const 对象的指针, con ...

  3. 高德携手阿里云发布“LBS云”,账户打通只是第一步

    位置.游戏.视频,是公认的基于云计算的三大移动端应用方向.而今,LBS云有了更多进展,在高价值应用与云平台之间实现了资源打通和融合,高德迈出了实质性的一步. 高德地图副总裁郄建军(左)与阿里云业务总经 ...

  4. 【整理】 JavaScript模块化规范AMD 和 CMD 的区别有哪些?

    根据玉伯等人在知乎上的回答整理.整理中... AMD 规范在这里:https://github.com/amdjs/amdjs-api/wiki/AMD CMD 规范在这里:https://githu ...

  5. 算法实质【Matrix67】

    动态规划 :你追一个MM的时候,需要对该MM身边的各闺中密友都好,这样你追MM这个问题 就分解为对其MM朋友的问题,只有把这些问题都解决了,最终你才能追到MM. 因此,该问题适用于聪明的MM,懂得“看 ...

  6. 从源码角度理清memcache缓存服务

    memcache作为缓存服务器,用来提高性能,大部分互联网公司都在使用.   前言    文章的阅读的对象是中高级开发人员.系统架构师. 本篇文章,不是侧重对memcache的基础知识的总结,比如se ...

  7. C语言关键字、标识符和注释

    一.关键字 C语言提供的有特殊含义的符号,共32个. 在Xcode中关键字全部高亮显示,关键字全部都为小写.如return.int等. 二.标识符 定义:标识符是程序员在程序中自定义的一些符号和名称. ...

  8. maven url

    aliyun阿里云Maven仓库地址--加速你的maven构建   maven仓库用过的人都知道,国内有多么的悲催.还好有比较好用的镜像可以使用,尽快记录下来.速度提升100倍. http://mav ...

  9. Training - An Introduction to Enterprise Integration

    What is EI? Enterprise Integration (EI) is a business computing term for the plans, methods, and too ...

  10. C# 泛型的协变和逆变

    1. 可变性的类型:协变性和逆变性 可变性是以一种类型安全的方式,将一个对象当做另一个对象来使用.如果不能将一个类型替换为另一个类型,那么这个类型就称之为:不变量.协变和逆变是两个相互对立的概念: 如 ...