【发布时间】:2018-08-01 08:13:10
【问题描述】:
假设我有这个代码:
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 更好?为什么?
【问题讨论】:
-
如果您将来将
MyObject重命名为其他名称怎么办?如果您采用第一种方法,则必须在两个地方进行更改。 -
好吧
this会让它更可重用.. -
只使用 this.b(x) ?
-
为什么
self = this...?! -
这里看起来有点荒谬:a(x) === b(x),那么这种模式真的有用例吗?
标签: javascript jquery object this