javascript - 为不同类中的方法提供“this”上下文的最佳实践
问题描述
我有 2 个类,其中一个是整个应用程序使用的通用实用程序类。我想this
在被调用者实用程序类中引用调用者类的属性。
我不确定最好的做法是什么。
我已经提供了一个我正在尝试做的例子。
我可以使用一种情况.call
来提供正确的上下文,或者我可以作为函数参数this
传入。this
class Caller {
doSomething() {
Utility.calledMethod.call(this, 'paramStr');
Utility.calledMethodWithThis(this, 'paramStr');
}
doAnotherThing(param) {
console.log(param);
}
}
// Shared Class of utility methods used for entire application
class Utility {
static calledMethod(param) {
this.doAnotherThing(param);
}
static calledMethodWithThis(self, param) {
self.doAnotherThing(param);
}
}
const caller = new Caller();
caller.doSomething();
解决方案
这看起来像是您可以使用 mixin 的场景。
按照此页面中的示例:https ://javascript.info/mixins
您的代码可能如下所示:
// Shared Class of utility methods used for entire application
let utilityMixin = {
calledMethod(param) {
this.doAnotherThing(param);
}
}
class Caller {
constructor() {
this.mystring = 'hello!'
}
doSomething() {
this.calledMethod(this.mystring);
}
doAnotherThing(param) {
console.log(param);
}
}
Object.assign(Caller.prototype, utilityMixin );
const caller = new Caller();
caller.doSomething();
推荐阅读
- reinforcement-learning - 在 Python 3 上的 Open AI Gym 实现中声明编码
- c++ - 与 XTR-DH Crypto++ 的密钥协议
- nginx - Lua 脚本可以从站点可用/启用站点的配置中获取变量吗?
- anaconda - Jupyter 笔记本,在哪里?
- c# - UWP 如何通知进程终止?
- javascript - 设法在html页面中下载文件依赖项
- angular - rxjs/operators:找不到模块
- java - Java编写仅在编译时运行的代码?
- php - 从xml填充数组?PHP/XML
- javascript - 使用 fetch POST 数据后自动刷新