JavaScript class 名称是什么对象的属性?

JavaScript class names are the properties of what object?

这与 CSS classes 无关,由于单词“class”与 JavaScript 相关,我的问题几乎找不到答案通常与 HTML CSS class 相关。至此无话可说。仅控制台对话框:

> function Foo() {}
< undefined
> window.Foo
< function Foo() {}
> class Bar {}
< undefined
> window.Bar
< undefined
> Foo
< f Foo {}
> Bar
< class Bar() {}
> window.Zoo
< undefined
> Baz
x Uncaught ReferenceError: Baz is not defined

在有 class 关键字之前,我们将 classes 定义为函数,这些名称最终成为 window 对象的属性(至少在浏览器中是这样)。 class 个名字现在在哪里?我怎样才能像 delete window.Foo 一样删除 class?如何测试 class has been defined 而不会出现 Name is not defined 错误?

首先,我们只是在谈论变量。您将全局变量的行为与 classes 混为一谈。 new-ish class 关键字只是围绕带有 let 的变量声明的语法糖,与 function(出于我们的目的)等同于 var 的方式相同。 类与您的问题无关。使用 let 声明的全局变量不再作为全局对象的属性出现,使用 class.

声明的变量也是如此

Before there was a class keyword we defined classes as functions and those names ended up properties of the window object

不,只有变量(所有变量,而不仅仅是“classes”)在全局范围内用varfunction定义最终作为全局对象的属性。 “class”(即构造函数)或在任何其他范围内声明的任何其他变量将绑定到该范围并且不会出现在全局对象上:

function Foo() { }
window.Foo // function Foo() { }
(function () { function Bar() { } })();
window.Bar // undefined

Where are the class names now?

它们一直在哪里,无论是用 functionvarletclass 声明:它们被声明的范围。使用 class 创建的构造函数只是您所在范围内的变量,就像变量一样。

{
  class Foo {}
} // Foo is gone

How can I delete a class as I can delete window.Foo

你不会这样做的。您只需让它超出范围,或者如果您出于某种原因真的想重用该变量,则将变量设置为 undefined

class Foo { }
Foo = undefined;

How can I test a class has been defined without getting a Name is not defined error?

对于所有变量,无论它们是如何声明的,就像您始终应该拥有的那样:typeof。您永远不应该检查 window 中的属性,因为这仅适用于 global 变量。

typeof Foo // "undefined"
class Foo { }
typeof Foo // "function"