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

查看:15
本文介绍了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 时,这在 angular 中很有用:

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) 
    });

在上面的例子中,函数内的thisnot引用$httpthis> 上下文,除非我们明确地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).

Partial Application 用于创建一个已经传递一些参数的函数.一个非常简单的例子:

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天全站免登陆