尝试使用Javascript原型删除多个代码重复

时间:2014-06-19 22:22:40

标签: javascript jquery prototype

在此代码中:

MyClass.prototype = {

    methodA: function() {
        var obj = this;

        $('#my-field').keyup(function(){
            obj.methodB();
        });
    },
    methodB: function() {
        var obj = this;

        $('.flag').click(function(){
            obj.methodC($(this), $(this).attr('data-id-flag'));
            obj.methodD();
        });
    },

    ...

}

有没有办法删除某些方法中存在的以下多重声明?

var obj = this;

我必须使用此原因解释in this question

1 个答案:

答案 0 :(得分:2)

我认为你的意思是如何将上下文传递给那些闭包。

您可以使用.bind(this)$.proxy(function(){}, this)

执行此操作
MyClass.prototype = {

    methodA: function() {

        $('#my-field').keyup($.proxy(function(){
            this.methodB();
        }, this));
    },
    methodB: function() {

        $('.flag').click($.proxy(function(e){
            var $el = $(e.currentTarget);
            this.methodC($el, $el.attr('data-id-flag'));
            this.methodD();
        }, this));
    },
}

bind docs

proxy docs