简体   繁体   中英

Why does “this.myFunction” not work when calling a function inside an object?

Here are two samples of code. The first one does not work and the second one does, though I'm completely at a loss as to why. Can someone explain this?

[I'm writing a simple game using a bit of jQuery to be played in a webkit browser (packaged with Titanium later).]

In the first example, Firebug tells me that "this.checkCloud" is not a function.

function Cloud(){

    this.checkCloud = function(){
      alert('test');            
    }

    $("#"+this.cloudName).click(function(){
        this.checkCloud();
    });

}

...but then this works:

function Cloud(){

    this.checkCloud = function(){
      alert('test');            
    }

    var _this = this;

    $("#"+this.cloudName).click(function(){
        _this.checkCloud();
    });

}

This one works perfect.

Why does the first one not work? Is it because "this.checkCloud" is inside of the anonymous function?

That is because the meaning of this can potentially change each time you create a new scope via a function. The meaning of this depends on how the function is invoked (and the rules can be insanely complicated). As you discovered, the easy solution is to create a second variable to which you save this in the scope where this has the expected/desired value, and then reuse the variable rather than this to refer to the same object in new function scopes where this could be different.

in this example:

$("#"+this.cloudName).click(function(){
        this.checkCloud();
    });

this referrers to the element selected(jquery object).

what you can do is use private functions

var checkCloud = function(){
      alert('test');            
    }

this way you can simply call it inside your anonymous function

$("#"+this.cloudName).click(function(){
            checkCloud();
        });

Try this:

function Cloud(){

    this.checkCloud = function(){
      alert('test');            
    }

    var func = this.checkCloud;

    $("#" + this.cloudName).click(function(){
         func();
     });
}

When you assign an even listener to an element, jQuery makes sure that this will refer to the element. But when you create the _this variable, you're creating a closure that jQuery couldn't mess with, even if it wanted to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM