我该怎么做。使用承诺和通用功能

How do I make this. work with promises and generic functions

我正在尝试做类似以下的事情:

function newCounter(){
    return {
        "counter" : 0
        ,"mode" : "new"
        ,"start" : function( arg_function ){
            //    Run this before counting.
            this.counter = 0;
            this.mode = "count";
        }
        ,"finished" : function(){
            // Run this when counting is no longer allowed.
            this.mode = "done";
        }
        ,"increment" : function(arg_key){
            globalThing.isValid(arg_key)
            .done(function(data){
                if( this.mode === "count" ){
                    this.counter++;
                }
            });
        }
    }
}

现在,正如人们可能注意到的那样,这里的问题是在 .done() 部分中,我引用了 this. - 它没有也不能引用有问题的对象因为它在具有通用函数的 promise 中,因此,指的是 window. 而不是从中引用的特定对象。我试过这些:

.done(function(data){
    if( this.mode === "count" ){
        this.counter++;
    }
}.apply(this))

.done(function(data){
    if( this.mode === "count" ){
        this.counter++;
    }
}.call(this))

作为解决方案,但他们没有成功。我不完全确定为什么。如果你能看到我在这里尝试做的事情......你能推荐一个解决我的困境的方法吗?

改用bind

.done(function(data){
    if( this.mode === "count" ){
        this.counter++;
    }
}.bind(this))

您始终可以在返回对象之前保留对对象的引用:

function newCounter(){
    var o = {
        "counter" : 0
        ,"mode" : "new"
        ,"start" : function( arg_function ){
            //    Run this before counting.
            o.counter = 0;
            o.mode = "count";
        }
        ,"finished" : function(){
            // Run this when counting is no longer allowed.
            o.mode = "done";
        }
        ,"increment" : function(arg_key){
            globalThing.isValid(arg_key)
            .done(function(data){
                if( o.mode === "count" ){
                    o.counter++;
                }
            });
        }
    }

    return o;
}