从回调函数调用其他函数

时间:2013-10-01 14:46:31

标签: javascript jquery

我有这样的事情:

var Tset = function(){
     this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
     $(this.a).mouseover(function(){
              this.setBackground('red');
     });  
     this.setBackground = function(_color){
        $(this.a).css({'background-color':'color'});
        }
}

var x = new Tset();

我的问题是我无法从this.setBackground回调函数调用mouseover。我怎么解决这个问题? 谢谢!

2 个答案:

答案 0 :(得分:5)

是的,在回调this内部引用的元素不是您实例的上下文。所以尝试缓存this

var Tset = function () {
    var self = this; //<-- cache this to be used later
    this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
    $(this.a).mouseover(function () {
        self.setBackground('red'); //invoke it with self
    });
    this.setBackground = function (_color) {
        $(this.a).css({
            'background-color': _color
        });
    }
}

var x = new Tset();

还有其他与此相似的技术,即使用Ecmascript5 function.bind$.proxy等。

使用绑定功能:

 var Tset = function () {

     this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
     $(this.a).mouseover((function () {
         this.setBackground('red'); //Now this will be your instanc's context
     }).bind(this)); //bind the context explicitly  
     this.setBackground = function (_color) {
         $(this.a).css({
             'background-color': _color
         });
     }
 }

除了绑定函数之外,调用者确定回调内的上下文

<强> Fiddle

答案 1 :(得分:2)

在jQuery事件处理程序中,this设置为发生事件的元素。

但是,在绑定回调的父函数中,您可以声明另一个变量来存储该函数的this,并在回调中引用该变量。

像这样:

var Tset = function(){
    var that = this;// Declare another variable to store the parent function's "this" value.

     this.a = $('div').text("lorem ipsum ..").appendTo('#a1');
     $(this.a).mouseover(function(){
              that.setBackground('red');// And refer to that variable in your callback.
     }); 
相关问题