Overwritten “this” variable problem or how to call a member function?

前端 未结 4 1223
小鲜肉
小鲜肉 2020-12-21 23:16

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

var MyClass = Class.create({
    initElements: function(sumEl) {
       this.sumEl          


        
4条回答
  •  醉梦人生
    2020-12-21 23:44

    It is the famous Javascript idiom you need to use in initElements function:

    var that = this;
    

    Later in your handler just refer to that instead of this:

    var MyClass = Class.create({
        initElements: function(sumEl) {
            this.sumEl = sumEl;
            var that = this;
            sumEl.keyup(this.updateSumHandler);
        },
        updateSumHandler: function(event) {
            that.updateSum();
        },
        updateSum: function() {
            // does something here
        }
    });
    

    It was covered in great detail in talk by Stuart Langridge on Javascript closures at Fronteers 2008 conference.

提交回复
热议问题