开发者

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

开发者 https://www.devze.com 2023-03-19 16:21 出处:网络
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?

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 gam开发者_开发知识库e 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?


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消