Dav*_*yon 38

Angular.bind是一个实用函数,它结合了function.bind部分函数应用程序中的功能.

绑定(通常)是您希望将当前上下文绑定到函数,但实际上稍后执行它的想法.

在使用$http和处理promises 进行HTTP调用时,这在角度方面很有用:

$http.get('url').then(angular.bind(this, 
    function(response) { 
        this.response = response; //use this (which is the bound context) 
    });
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,this在函数内部会不会this$http背景下,除非我们明确bind了.这是一个常见的JavaScript问题(在回调中),因为它的上下文动态绑定(这与大多数流行的面向类的语言不同).

当您想要创建一个已经传递了一些参数的函数时,使用部分应用程序.一个非常简单的例子:

function add(x, y) { 
    return x + y; 
}

var add10To = angular.bind(this, add, 10);

console.log(add10To(5));
// outputs 15
Run Code Online (Sandbox Code Playgroud)

通过Angular.bind,Angular团队将这两者结合在一起.


Sul*_*han 7

这是函数式语言所基于的经典函数之一.它允许我们使用部分功能.请注意,这不是特定于角度的,这是特定于Javascript的.Javascript的大多数实用程序库也包含此功能(例如Underscore/Lodash).

如今,这个函数是Javascript本身的一部分(在所有主流浏览器上都支持 - 请参阅哪些浏览器支持bind()?).

要解释什么bind呢,我将把Lodash文档中(替换原始的例子_.bindangular.bind,并增加了一些评论):

//this is a simple function. Note it uses "this" but it's not inside any object.
var greet = function (greeting, punctuation) {
  return greeting + ' ' + this.user + punctuation;
};

//now let's define an object
var object = { 'user': 'fred' };

//now we can create a functions by "binding" the object with the function above and also supplying the "greeting" argument
var bound = angular.bind(object, greet, 'hi');
bound('!');
// ? 'hi fred!'
Run Code Online (Sandbox Code Playgroud)