【问题标题】:Call function inside event handler oop在事件处理程序 oop 中调用函数
【发布时间】:2013-11-30 14:06:28
【问题描述】:

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

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/

【问题讨论】:

  • @TusharGupta 哇,不要把你的编码风格强加给别人的问题。那是完全不恰当的编辑。
  • 另一个选项:.click(function(){ this.Go() } .bind(this));我喜欢这样,因为 e.target 将引用“旧 this”,也就是被点击的元素。你也可以只做 .click(this.Go.bind(this));

标签: javascript jquery oop


【解决方案1】:

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

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

【讨论】:

  • 作为解释:this 是一个有点神奇的变量,不能被关闭,所以上下文在你的点击处理程序中丢失了。您需要将它放在一个可以关闭的变量中,而这样做的一种非常常见的方法是使用一个名为self 的变量。这个变量没有什么神奇之处,它只是一种常见的约定。
  • self 本身不是全局上下文标识符吗?
  • @bergman - 嗯...是的。但在这种情况下,它是一个局部变量,因为它是在带有var 的函数内声明的(如果需要,相同的函数可以使用window.self 引用全局变量)。随意使用其他名称...
【解决方案2】:

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

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

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

【讨论】:

  • 无需添加return 语句。还有,为什么yo突然变成私有变量了?
  • @nnnnnn yo 仍然是一个实例变量,因为它绑定到 Test 的特定实例。
  • @meagar - 是的,但我的意思是你不能使用test.yo。我已将评论编辑为“私人”而不是“实例”。
  • @nnnnnn 不,在这个意义上它是“私人的”。
  • @nnnnnn "不需要添加return语句。" - 我同意,在这个例子中不需要。只是一个习惯,以防万一,例如那 = 新的超级测试()。我让你“私人”让 OP 有更多的思考,因为他正在走向古典方法,我认为他可能会发现它很有用。已编辑,谢谢。
【解决方案3】:

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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多