首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当我使用另一个模块类时,如何修复"TypeError:'instanceof‘的右侧不可调用“?

当我使用另一个模块类时,如何修复"TypeError:'instanceof‘的右侧不可调用“?
EN

Stack Overflow用户
提问于 2019-06-21 05:02:36
回答 1查看 42.7K关注 0票数 10

我试图检查上下文的类型是否是上下文的实例,它位于另一个文件中,但是节点js抛出TypeError: Right-hand side of 'instanceof' is not callable.

index.js

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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文件

代码语言:javascript
运行
复制
let context = new Context('some uid');
context.runTransaction((transaction) => {
});

在那里,它抛出了TypeError: Right-hand side of 'instanceof' is not callable

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-21 05:04:04

问题是,您有一个循环依赖项。另一个文件需要indexindex需要TransactionTransaction需要index。因此,当transaction运行时,它试图要求index,它的模块已经在构建过程中。index还没有导出任何东西,所以当时需要它会导致一个空对象。

由于两者必须相互调用,解决这一问题的一种方法是将两个类放在一起,并同时导出它们:

代码语言:javascript
运行
复制
// 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 };

代码语言:javascript
运行
复制
const { Context, Transaction } = require("./index");
const context = new Context("some uid");
context.runTransaction(transaction => {});

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

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56697115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档