Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

javascript循环依赖

我建了三个类分别为Stmt,IfStmt,WhileStmt,其中Stmt为基类,后两个为派生类我把他们分别保存在三个文件中,其中IfStmt,WhileStmt引入了Stmt文件,Stmt也引入了IfStmt,WhileStmt,然后在执行的时候出现了这个错误
class extends value undefined is not a constructor or null

在线代码地址(包含了tsconfig.json)

Stmt.ts

import { Stmt } from "./Stmt";
export class IfStmt extends Stmt {
  static parse(source: string): void {
    console.log("IfStmt.parse");
  }
}

WhileStmt.ts

import { Stmt } from "./Stmt";
export class WhileStmt extends Stmt {
  static parse(source: string): void {
    console.log("WhileStmt.parse");
  }
}

Stmt.ts

import { IfStmt } from "./IfStmt";
import { WhileStmt } from "./WhileStmt";
export class Stmt {
  static parseStmt(source: string): void {
    if (source === "if") IfStmt.parse(source);
    else if (source === "while") WhileStmt.parse(source);
  }
}

感觉这个需求还是挺常见的,除了全部写在一个文件里,还有没有什么好的办法。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

典型的反设计模式。

基类怎么能“预先”知道子类呢?

你现在放到基类的那坨代码,应该再抽一个工厂类出来,就是一个简单的工厂模式。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...