0

I am trying to do something rather like the following:

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++;
                }
            });
        }
    }
}

Now, the problem here, as one may notice, is that inside the .done() section there, I have a reference to this. - which does not and cannot refer to the object in question because it's inside a promise with a generic function, and as such, refers to window. and not the specific object being referenced from. I have tried these:

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

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

as solutions, but they have not succeeded. I'm not entirely sure why. If you can see what I'm trying to do here ... could you recommend, please, a solution to my woes?

Wolfman Joe
  • 799
  • 1
  • 8
  • 23

2 Answers2

2

Use bind instead:

.done(function(data){
    if( this.mode === "count" ){
        this.counter++;
    }
}.bind(this))
taxicala
  • 21,408
  • 7
  • 37
  • 66
0

You can always keep a reference to the object before returning it:

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;
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93