开发者

How do I call this function from within JQuery?

I want to use JQuery in a Javascript program I'm working on but I ran into some issues with scope.开发者_开发百科 How do I call myfunction2 from myfunction1 in this psuedo-code? (assume that a new MyConstructor object has been created somewhere and that myfunction1() has been called)

function MyConstructor(){...}

MyConstructor.prototype.myfunction1 = function(param) {
   $('#some_element').click(function(){
    this.myfunction2('clicked!'); //this doesn't work
  });
}

MyConstructor.prototype.myfunction2 = function(param) {

}


myfunction2 can be called with this.myfunction2() when in any function of MyConstructor.

In your case you are trying to call myfunction2 inside another function that has a different meaning for this. To access myfunction2 you can create a variable for either this or this.myfunction2 that is in closure scope that extends to the function parameter of click

var self = this; 
$('#some_element').click(function(){
   self.myfunction2('clicked!');
});

or

var myfunction2 = this.myfunction2; 
$('#some_element').click(function(){
   myfunction2('clicked!');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜