javascript - 自动绑定JS类方法的好方法是什么?
问题描述
我厌倦了编写这样的代码:
class Something {
constructor() {
this.method = this.method.bind(this);
this.anotherOne = this.anotherOne.bind(this);
// ...
}
}
这很耗时,而且很容易忘记绑定方法。我知道类字段提案,但它仍然是第 3 阶段,似乎有一些问题。
我当前的解决方案(基于此答案)如下所示:
class Something {
constructor() {
// Get all defined class methods
const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(this));
// Bind all methods
methods
.filter(method => (method !== 'constructor'))
.forEach((method) => { this[method] = this[method].bind(this); });
}
}
这似乎可行,但我想知道是否有更好的方法,或者这种方法是否存在我不知道的问题。
更新:为什么要这样做?
我遇到的问题是,如果我不在构造函数中绑定我的类函数,我必须记住稍后“正确地”调用它们。例如:
const classInstance = new Something();
// This fails for a non-obvious reason
someAction()
.then(classInstance.method);
// This works of course but looks like we created a useless function if you don't know better
someAction()
.then(result => classInstance.method(result));
解决方案
推荐阅读
- c# - 如何保存我的对象并使用 XML 而不是 .txt 显示它们?
- c++ - 如何使用“SHCreateDefaultContextMenu”为来自不同文件夹的多个文件显示 shell 上下文菜单
- ruby-on-rails - 将 mongoDB 迁移到 Rails 上的 AWS DocumentDB db 无法创建索引
- c++ - 运行 cmake + make 时如何指定调用哪个编译器?
- python - 如何使用 python 在 Webbot 中获取 $0 值
- django - Django Admin - 更改字段模型并自动更新另一个模型
- r - 如何制作斜体的图表字体?(ggplot2 和 factoextra 包)
- loops - 在向量中展开(开始,结束)对
- android - 如何将 Ints 从 datePicker 格式化为日期字符串
- arrays - 在 postgresql 中按键优化对象的总和数组数组