首页 > 解决方案 > 调用 self 对象方法时的最佳实践

问题描述

假设我有这个代码:

const MyObject = {
    a($els) {
        // What is the best practice here ?
        $els.each(function() {
            MyObject.b($(this));
        });
        // Or
        const self = this;
        $els.each(function() {
            self.b($(this));
        });
    },
    b($el) {
        $el.addClass('test');
    }
};

在对象中调用另一个方法的“最佳实践”是什么?调用变量“MyObject”有什么缺点吗?还是更好用this,为什么?

标签: javascriptjqueryobjectthis

解决方案


没有错

this.method(params)

但是,如果您有嵌套范围,则this可能意味着不同的东西并且很快就会变得混乱。为避免这种情况,请使用var self = this创建另一个指向右侧的变量this

例子:

const MyObject = {
    a(x) {
        var self = this;
        return x.map(function (a) 
        {
           // cannot use this here to access parent scope
           return self.b(a);
        })


    },
    b(y) {
      return y % 2;
    }

};


推荐阅读