覆盖“this"变量问题或如何调用成员函数? [英] Overwritten "this" variable problem or how to call a member function?

查看:21
本文介绍了覆盖“this"变量问题或如何调用成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个类,我使用 jQuery 和 Prototype 的组合::p>

I have this class where I am using a combination of jQuery and Prototype:

var MyClass = Class.create({
    initElements: function(sumEl) {
       this.sumEl = sumEl;
       sumEl.keyup(this.updateSumHandler);
    },

    updateSumHandler: function(event) {
       // Throws error here: "this.updateSum is not a function"
       this.updateSum();
    },

    updateSum: function() {
       // does something here
    }
});

我到底如何调用 this.updateSum()?

推荐答案

你需要使用闭包.

 initElements: function(sumEl) {
        this.sumEl = sumEl;
        var ref = this;
        sumEl.keyup( function(){ref.updateSumHandler();});
 },

这篇关于覆盖“this"变量问题或如何调用成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆