node.js - 这是在扩展类中未定义的
问题描述
我有这 3 个文件:
bar.js
class Bar {
test(p) {
console.log(p);
}
}
module.exports = Bar;
baz.js
const Bar = require('./bar');
class Baz extends Bar {
test2(p) {
this.test(p);
}
}
module.exports = Baz;
foo.js
const Baz = require('./baz');
const { test2 } = new Baz();
test2('test');
当我传递'test'
给 时new Baz.test2()
,我希望它将它传递给this.test(p)
它应该记录的超类 () 'test'
。但是,它抛出了错误:
this.test(p);
^
TypeError: Cannot read property 'test' of undefined
我究竟做错了什么?为什么是this
未定义的,我认为它应该引用类本身?
解决方案
test2
与原始上下文(实例)分开使用Bar
,应绑定到正确的this
.
如果预期它是设计上的回调,则无法从名称中说出来。如果是,它可以在构造函数中绑定:
class Bar {
constructor () {
this.test = this.test.bind(this);
}
...
}
否则它可以就地绑定:
const test2 = new Baz().test2.bind(this);
test2('test');
或者只是不与上下文分开使用:
const baz = new Baz()
baz.test2('test');
推荐阅读
- ios - RxDataSources tableView 具有来自一个 API 源的多个部分
- email - AWS EC2 通用嫌疑人
- angular - 如何查看离子选择组件完整列表中的选定项目?
- python - Python - 根据标识符列从以前的行中按值填充 NA
- java - HibernateCursorItemReader 获得对会话错误的非线程安全访问
- php - 如何解压 gzip 请求 PHP/Lumen/Laravel?
- google-api - 是否有特定的 Google OAuth v2 刷新令牌 URL?
- excel - Excel 中 =FLOOR() 方程的准确性不一致
- c# - Angular 中的 HTTP 响应提供 200 但从未到达服务器
- ios - iOS模拟器中出现强密码自动填充