javascript - 从回调函数中调用其他函数

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

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

最佳答案

是的,在回调中 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等等

使用绑定(bind)函数:

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

除了绑定(bind)函数之外,调用者决定回调内的上下文

<强> Fiddle

关于javascript - 从回调函数中调用其他函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19119286/

相关文章:

javascript - 无法理解这里每种方法是如何工作的

javascript - 无法使用拖动控件

java - jnlp 文件没有 .jnlp 扩展名? jnlp 负责启动沙箱吗?

javascript - 使用 webpack 加载 requirejs 模块的 css 依赖

jquery - 如何让 jQuery .expander 在加载时调用,而不仅仅是在单击时调用?

javascript - 如何在 JavaScript 函数的条件中使用 Bootstrap 模式

javascript - 为什么我的全局自定义 jQuery 函数没有被调用?

javascript - Jquery 将 JSON 发布到本地文件

javascript - 从对象中提取键时,对象有一个额外的属性

javascript - 由于错误 editor-incorrect-element,CKEditor 4 无法正常工作