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. IT技术开发人员获得成功的六大步骤

    IT技术开发人士成功的6大步骤 一个前辈在移民加拿大后写的文章,写得不错,值得借鉴,转来给大家看看,也给自己   序言:经过001多年的洗礼,认识了这里这么多的JJMMGGDD,前几天刚得到签证, 无 ...

  2. iOS6.0下获取通讯录用户列表

    自iOS6.0后获取通讯录列表需要询问用户,经过用户同意后才可以获取通讯录用户列表.而且ABAddressBookRef的初始化工作也由ABAddressBookCreate函数转变为ABAddres ...

  3. VS2010下安装Cocos2dx完整教程(原)

    一.本人所使用的Cocos2dx版本(cocos2d-2.1rc0-x-2.1.3),下载地址:http://code.google.com/p/cocos2d-x/downloads/list 当前 ...

  4. html的head里出现了 http://c.cnzz.com/core.php

    网站里出现了一段代码, 有点强迫症的我就受不了了: <html lang="en"> <head> <title>登录</title> ...

  5. Fiddler (三) Composer创建和发送HTTP Request

      之前已经写过两篇Fiddler的文章了,分别是[Fiddler教程] [Fiddler script用法].  我准备把Fiddler写成一个系列. Fiddler的功能还有很多, 很多功能都没有 ...

  6. Android APP测试的日志文件抓取

         1    log文件分类简介 实时打印的主要有:logcat main,logcat radio,logcat events,tcpdump,还有高通平台的还会有QXDM日志 状态信息的有: ...

  7. cnodejs社区论坛6--评论功能

  8. 每天一命令 git stash

    git stash  命令是用于保存当前进度的命令.该命令会保存当前工作区的改动.保存的改动是已经跟踪的文件的改动,对于未跟踪的改动stash是不会保存的. git stash 命令常用于分支切换的 ...

  9. Popline:帅气的浮动 HTML5 文本编辑器工具栏

    Popline 是一个基于 HTML5 实现的富文本编辑器工具栏,设计灵感来自 PopClip ,相比传统的文本编辑器工具,Popline 能够浮动在编辑的文本周围,操作起来十分方便. 您可能感兴趣的 ...

  10. 推荐15款最佳的响应式 Web 设计测试工具

    响应式网页设计是根据设备的屏幕尺寸,平台和方向来开发的网页,是一种对最终用户的行为和环境作出反应的方法.响应式设计使用灵活的网格和布局,图像和智能使用 CSS 媒体查询的组合.当从它们在不同设备使用的 ...