Javascript 回调方法不更新 AngularJS 除非在 shorthand 形式

Javascript callback method not updating AngularJS unless in shorthand form

在以下两个嵌入 angular 控制器的片段中,用于登录用户(取自 angular-meteor tutorial):

    this.login = function() {
        Meteor.loginWithPassword(this.credentials.email, this.credentials.password, (err) => {
            if (err) {
                this.error = err.reason;
            }
            else {
                $state.go('index');
            }
        });
    };

和:

    this.login = function() {
        Meteor.loginWithPassword(this.credentials.email, this.credentials.password, function(err) {
            if (err) {
                this.error = err.reason;
            }
            else {
                $state.go('index');
            }
        });
    };

第一个导致 AngularJS 在回调后更新错误值,但第二个代码段不触发更新。唯一的区别是在第一个中使用了 shorthand 方法声明。这是什么原因?

这不仅仅是 shorthand,第一个使用 arrow function。箭头函数对待它们的作用域不同于 function lambda。

箭头函数继承它们的父作用域。因此,无需在内部绑定 this(对于此示例)。

如果您使用 function lambda,则必须 bind this:

this.login = function() {
        Meteor.loginWithPassword(this.credentials.email, this.credentials.password, function(err) {
            if (err) {
                this.error = err.reason;
            }
            else {
                $state.go('index');
            }
        }.bind(this));
    };