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

Trying to remove multiple code duplication using Javascript prototype

本文关键字:代码 删除 原型 Javascript      更新时间:2023-09-26

在此代码中:

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;

我必须使用这个的原因在这个问题中解释了。

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

您可以使用.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));
    },
}

绑定文档代理文档