javascript - 调用 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
,为什么?
解决方案
没有错
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;
}
};
推荐阅读
- json - Laravel 在正文中发送 JSON 标头
- reactjs - React-Redux - 调度时出错 - TypeError
- java - Graphics2D.drawImage(从 BufferedImage 获得)和 BufferedImage.setRGB() 在 Java 中填充 BufferedImage 有什么区别?
- c# - 所有导航属性的模型状态错误
- c# - 获取每个批量插入操作中插入的行数
- wcf - Flutter WCF 服务调用
- android - 应用程序在模拟器上运行良好,但在我的设备上运行时它不会登录/注册
- c - 在 ffmpeg 复杂过滤器初始化中出错
- teamcity - 循环遍历 TeamCity 中的一组构建
- node.js - 如何在 node.js 环境中将查询语句传递给 bigquery