Javascript 再语言承诺功能的范围

Javascript 再语言承诺功能的范围,javascript,angularjs,restangular,Javascript,Angularjs,Restangular,我试图理解我在restangular服务中调用的then函数的范围。只有当重新启动的承诺解决时,我才尝试调用服务中的函数 angular.module('app').service('test', function(rest) { this.doSomething = function() { console.log(this); // this logs the current object im in rest.getSomething().then(

我试图理解我在restangular服务中调用的then函数的范围。只有当重新启动的承诺解决时,我才尝试调用服务中的函数

angular.module('app').service('test', function(rest) {
    this.doSomething = function() {
        console.log(this); // this logs the current object im in
        rest.getSomething().then(function(data) {
            console.log(this); // this logs the window object
            this.doSomethingElse(); // this is what I want to call but is is not in scope and I cant seem to get my head around as to why.
        }
    };
    this.doSomethingElse = function() {
        // Do something else
    };
});

您可以在then回调中使用缓存的
this

angular.module('app').service('test', function (rest) {
    this.doSomething = function () {
        var self = this; // Cache the current context

        rest.getSomething().then(function (data) {
            self.doSomethingElse(); // Use cached context
        });
    };

    this.doSomethingElse = function () {
        // Do something else
    };
});
您还可以将函数引用用作

rest.getSomething().then(this.doSomethingElse);