在事件处理程序oop中调用函数

时间:2013-11-30 14:06:28

标签: javascript jquery oop

如何调用方法从事件处理程序内部转到?

function Test()
{
    this.yo = "YO";

    this.Go = function()
    {
       alert(this.yo);        
    }

    $(".aha").click(function()
    {
          //Call Go();        
    });
}

var test = new Test();

小提琴: http://jsfiddle.net/BkNfY/9/

3 个答案:

答案 0 :(得分:3)

一种常见的方法是在构造函数中使用一个局部变量作为对实例的引用:

function Test()
{
    var self = this;

    this.yo = "YO";

    this.Go = function(){
       alert(this.yo);        
    }

    $(".aha").click(function(){
          self.Go();        
    });
}

或者您可以bind传递给.click()的功能:

    $(".aha").click(function(){
          this.Go();        
    }.bind(this));

答案 1 :(得分:3)

http://jsfiddle.net/BkNfY/12/

function Test(){
    var that = this;

    that.yo = "YO";

    that.go = function(){
       alert(that.yo);        
    }

    $(".aha").click(function(){
       that.go();        
    });

    return that;
}

var test = new Test();

但这样做更有意义:(如果你想重用Test)

function Test(){
    var that = this;

    that.yo = "default YO";

    that.go = function(){
       alert(yo);        
    }

    return that;
}

var test = new Test();
test.yo = "YO";

$(".aha").click(function(){
     test.go();        
});

如果不在Test之外使用,你可以保持“私密”,例如test.yo

function Test(){
    var that = this,
        yo = "YO"; // yo is now "private"
                   // so can't modify yo from outside of this function

    that.go = function(){
       alert(yo);        
    }

    return that;
}

var test = new Test();

$(".aha").click(function(){
     test.go();        
});

答案 2 :(得分:0)

jQuery方式:

$('.aha').click($.proxy(function (e) {
    // e.target refers to the clicked element
    this.Go();
}, this));

更短:

$('.aha').click($.proxy(this.Go, this));
$('.aha').click($.proxy(this, 'Go'));

http://api.jquery.com/jQuery.proxy/