函数(){}.bind(this) 和 angular.bind(this, function() {}) 之间的区别

Difference between function(){}.bind(this) and angular.bind(this, function() {})

本文关键字:bind this 之间 区别 function 函数 angular      更新时间:2023-09-26

以下代码有什么区别

function Ctrl($scope) {
    $scope.$watch(function() {
        return this.variable;
    }.bind(this), /*...*/);
}

function Ctrl($scope) {
    $scope.$watch(angular.bind(this, function() {
        return this.variable;
    }, /*...*/);
}

对我来说是一样的,但是使用angular.bind有什么好处吗?

内置的

Function.prototype.bind函数在较旧的浏览器中不存在,例如IE 8。但是,使用填充代码可以实现相同的语法。这本质上是Angular在内部所做的。

angular.bind函数不使用 Function.prototype.bind ,因此可以在较旧的浏览器中使用它。当然,如果您使用的是不主动支持那些旧浏览器的 Angular 版本,这一点是没有意义的。