gpt4 book ai didi

javascript - 当我使用另一个模块类时,如何修复 "TypeError: Right-hand side of ' instanceof' is not callable"?

转载 作者:行者123 更新时间:2023-11-30 13:59:03 26 4
gpt4 key购买 nike

我试图检查上下文的类型是否是另一个文件中的上下文实例,但是 Node 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

最佳答案

问题是您有一个循环依赖。另一个文件需要 indexindex 需要 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 => {});

https://codesandbox.io/s/naughty-jones-xi1q4

关于javascript - 当我使用另一个模块类时,如何修复 "TypeError: Right-hand side of ' instanceof' is not callable"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56697115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com