当我使用另一个模块类时,如何解决“ TypeError:'instanceof'的右侧不可调用”的问题?

时间:2019-06-21 05:02:36

标签: javascript node.js

我试图检查上下文的类型是否是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

1 个答案:

答案 0 :(得分:1)

问题是您具有循环依赖项。另一个文件需要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