我在脚本中声明了一个类,如下所示;
class XYPT {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
由于某些原因,我必须使用 jquery getscript 方法多次加载此脚本。当我尝试定义此类时,它给我一个错误“标识符‘XYPT’已被声明”。
是否可以检查一个类之前是否声明过?我正在寻找这样的东西,
(isDeclaredBefore(XYPT))
{
//do nothing
}
else
{
class XYPT {
constructor(x, y) {
this.x = x;
this.y = y;}
}
}
最佳答案
你的问题很合理。
每个人都应该首先组织代码和导入以防止类重新声明,但在极少数情况下,您可以在声明之前检查类是否存在。
已建议@Eldar,我们将使用类表达式
,但他的示例并不是最容易理解的。
if (typeof window.MyClassFooBar === 'undefined') {
window.MyClassFooBar = class {
constructor(settings) {
this.settings = settings;
}
doStuff() {
/* ... */
}
}
}
关于javascript - JS中如何避免重复的类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021187/