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

Javascript 事件处理程序oop中的调用函数,javascript,jquery,oop,Javascript,Jquery,Oop,如何从事件处理程序内部调用方法Go function Test() { this.yo = "YO"; this.Go = function() { alert(this.yo); } $(".aha").click(function() { //Call Go(); }); } var test = new Test(); 小提琴: 一种常见的方法是在构造函数中有一

如何从事件处理程序内部调用方法Go

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

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

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

var test = new Test();
小提琴:

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

function Test()
{
    var self = this;

    this.yo = "YO";

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

    $(".aha").click(function(){
          self.Go();        
    });
}
或者,您可以使用传递给
的函数。单击()

但这样做更有意义:(如果您想重用测试)

如果您不打算在测试之外使用yo,您可以将其保留为“私有”,例如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();        
});
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'));

作为解释:
这个
是一个有点神奇的变量,无法关闭,因此上下文在单击处理程序中丢失。您需要将它放在一个可以关闭的变量中,一种非常常见的方法是使用名为
self
的变量。这个变量并没有什么神奇之处,它只是一个比较常见的约定。self本身不是一个全局上下文标识符吗?@bergman-嗯……是的。但在这种情况下,它是一个局部变量,因为它是在一个带有
var
的函数中声明的(如果需要,相同的函数可以使用
window.self
引用全局函数)。请随意使用其他名称…@TusharGupta哇,不要把你的编码风格强加给别人的问题。这是一个完全不恰当的编辑。另一个选项:。单击(函数(){this.Go()}.bind(this));我喜欢这样,因为e.target将引用“旧this”,也就是被单击的元素。你也可以这样做。点击(this.Go.bind(this));不需要添加
return
语句。还有,为什么
yo
突然变成了一个私有变量?@nnnnnn
yo
仍然是一个实例变量,因为它绑定到
Test
@meagar的特定实例-是的,但我的意思是不能使用
Test.yo
。我已将我的评论编辑为“private”而不是“instance”。@nnnnnn否,从这个意义上说它是“private”。@nnnnnn“没有必要添加return语句。”-我同意,在本例中不需要。只是一种习惯,如果我们这样做的话,例如,this=new SuperTest()。我让你“私人”给OP更多的思考,因为他正在走向古典主义的方法,我想他可能会发现它有用。谢谢。
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();        
});
$('.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'));