3

我想将函数绑定到事件,但我想更改调用函数的上下文

function Foo(){

  t : "123",
  bar: function(){
    // I am here
    $('#selector').bind('click' this.foo);
  }
  ,
  foo: function(){
    //I want when to be able to use the current object here by this
    //this.t should be 123 and this.bar should call the above function
  }
}
4

2 回答 2

5

您可以使用jQuery.proxy

$('#selector').bind('click', $.proxy(this.foo,this) );
于 2012-06-16T19:55:36.933 回答
1

将对对象的引用复制到局部变量,并在函数中使用它:

var me = this;
$('#selector').bind('click' function() { me.foo(); });

如果您需要事件对象,请将其传递:

var me = this;
$('#selector').bind('click' function(e) { me.foo(e); });
于 2012-06-16T19:50:21.740 回答