angularjs中angular.bind的用途是什么?在哪里使用? [英] what is the use of angular.bind in angularjs? Where to use it?

查看:64
本文介绍了angularjs中angular.bind的用途是什么?在哪里使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angularjs中angular.bind的用法是什么.请提供一个例子.无法从 https://docs.angularjs.org/api/ng/function/angular.bind

what is the use of angular.bind in Angularjs. Please provide with a example. Cant understand from https://docs.angularjs.org/api/ng/function/angular.bind

推荐答案

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

Angular.bind is a utility function that combines functionality in function.bind and partial function application.

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

Binding (in general) is the idea that you want to bind the current context to a function, but actually execute it at a later time.

当使用$http进行HTTP调用并处理Promise时,这在有角度时很有用:

This can be useful in angular when making HTTP calls with $http and handling promises:

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

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

In the above example, the this inside the function would not refer to the this in the $http context unless we explicitly bind it. This is a common JavaScript issue (in callbacks) because of its dynamic binding of context (which is unlike most popular class-oriented languages).

部分应用程序是在您要创建已传递其参数 some 的函数时使用的.一个非常简单的例子:

Partial Application is used when you want to make a function that has already been passed some of its arguments. A very simple example:

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

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

console.log(add10To(5));
// outputs 15

有了Angular.bind,Angular团队会将这两个包裹在一起.

With Angular.bind, the Angular team is giving both of these wrapped up together.

这篇关于angularjs中angular.bind的用途是什么?在哪里使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆