我试图检查上下文的类型是否是Context的实例,该实例在另一个文件中,但是节点js抛出TypeError: Right-hand side of 'instanceof' is not callable.
index.js
const Transaction = require('./Transaction');
class Context {
constructor(uid) {
if (typeof uid !== 'string')
throw new TypeError('uid must be a string.');
this.uid = uid;
}
runTransaction(operator) {
return new Promise((resolve, reject) => {
if (typeof operator !== 'function')
throw new TypeError('operator must be a function containing transaction.');
operator(new Transaction(this))
});
}
}
module.exports = Context;
Transaction.js
const Context = require('./index');
class Transaction {
constructor(context) {
// check type
if (!(context instanceof Context))
throw new TypeError('context should be type of Context.');
this.context = context;
this.operationList = [];
}
addOperation(operation) {
}
}
module.exports = Transaction;
另一个js文件
let context = new Context('some uid');
context.runTransaction((transaction) => {
});
在那里,它抛出了TypeError: Right-hand side of 'instanceof' is not callable
。
答案 0 :(得分:1)
问题是您具有循环依赖项。另一个文件需要index
,index
需要Transaction
,而Transaction
需要index
。因此,当transaction
运行时,它试图要求index
,其模块已经在构建过程中。 index
尚未导出任何内容,因此当时要求导出该对象会导致一个空对象。
因为两者都必须互相调用,所以解决该问题的一种方法是将两个类放在一起,然后将它们都导出:
// index.js
class Context {
constructor(uid) {
if (typeof uid !== "string") throw new TypeError("uid must be a string.");
this.uid = uid;
}
runTransaction(operator) {
return new Promise((resolve, reject) => {
if (typeof operator !== "function")
throw new TypeError(
"operator must be a function containing transaction."
);
operator(new Transaction(this));
});
}
}
class Transaction {
constructor(context) {
// check type
if (!(context instanceof Context))
throw new TypeError("context should be type of Context.");
this.context = context;
this.operationList = [];
console.log("successfully constructed transaction");
}
addOperation(operation) {}
}
module.exports = { Context, Transaction };
和
const { Context, Transaction } = require("./index");
const context = new Context("some uid");
context.runTransaction(transaction => {});