从回调函数调用其他函数

Osk*_*ons 0 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();
Run Code Online (Sandbox Code Playgroud)

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

PSL*_*PSL 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();
Run Code Online (Sandbox Code Playgroud)

还有其他类似的技术,使用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
         });
     }
 }
Run Code Online (Sandbox Code Playgroud)

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

小提琴