问题
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