Javascript: extend classes with undefined class

点点圈 提交于 2020-07-22 21:34:30

问题


Consider the following two files:

/* file A.js */
class A extends B {

}

/* file B.js */
class B {

}

If I accidentaly load these two files into the browser in the inverse order (A.js first then B.js) javascript will throw an error, that I am trying to access B that is undefined.

My problem is, that I have to deal with around 30-40 classes defined in Javascript, and right now, for all of them to work, I have to keep in mind the order in which I want to include them in the page, or otherwise, javascript will throw an error that I am using something that is undefined.

How could I resolve this issue, so I don't have to constantly keep in mind the order in which these classes are loaded into the web page?


回答1:


I'd resolve it by using modules. Modules declare their dependencies explicitly and you only have to reference the top-level module in the page; the rest will be loaded according to the dependency tree. So for instance, B.js would be:

export class B {
    // ...
}

Then A.js would be:

import { B } from "./B.js";
export class A extends B {
    // ...
}

Perhaps your main entry point (main.js or whatever) would have:

import { A } from "./A.js";
// ...

Then your page has

<script type="module" src="./main.js"></script>

...and the other dependencies are loaded as needed.

This works with native module support in browsers, and/or if you use a bundler like Rollup.js, Webpack, ...



来源:https://stackoverflow.com/questions/59918447/javascript-extend-classes-with-undefined-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!