javascript - 将变量定义为一个方法,该方法是包含该变量的方法的调用者
问题描述
这很难用一个句子作为标题来解释,但基本上我正在处理一个导致错误的 TypeScript 文件。这是一个带有模拟问题代码的 TypeScript 游乐场;JS中的代码与TS中的代码基本相同。
这是 TS 操场外的代码:
const A = (class A {
b() {
const d = this.d;
d();
}
d() {
const b = this.b;
}
})
new A().b()
这是错误:
Uncaught TypeError: Cannot read property 'b' of undefined
at d (eval at <anonymous> (main-3.js:1241), <anonymous>:8:24)
at A.b (eval at <anonymous> (main-3.js:1241), <anonymous>:5:9)
at eval (eval at <anonymous> (main-3.js:1241), <anonymous>:11:9)
at main-3.js:1241
在维护变量声明别名的同时如何避免这种情况的任何帮助都会很有用。
谢谢!
解决方案
调用该d()
方法,this.d()
并将this
在该方法中定义:
const A = class {
b() {
const d = this.d;
this.d();
}
d() {
const b = this.b;
console.log(b);
}
};
new A().b();
推荐阅读
- drupal - Drupal 8分类术语相同级别
- javascript - 如何在 HTML 中调试换行(回车)事件
- android - Android 意图选择器 - 导航应用
- django - DRF:聚合相似条目名称
- java - OSGi - 如何通过现有的 bndrun 文件运行新的捆绑包
- python - 在 plpython3u 过程中导入 Python 包时出现“未找到模块”
- servicenow - 调度控制指标脚本的执行
- gcc - 如何为 GCC 8.1.0 添加调试符号?
- sql - 如何使用 SQL 复制 csv 文件
- python - 如何处理 Garmin 设备中的 timestamp_16?