以下代码有什么区别
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
函数,such as IE 8 。但是,可以通过使用 polyfill 来实现相同的语法。 。 This本质上就是 Angular 内部所做的事情。
angular.bind
函数不使用 Function.prototype.bind
,因此可以在较旧的浏览器中使用它。当然,如果您使用的 Angular 版本不主动支持那些旧版浏览器,这一点就没有意义。
关于javascript - function(){}.bind(this) 和 angular.bind(this, function() {}) 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28011228/