ES6中的类声明和类表达式 [英] Class declarations and Class expressions in ES6
问题描述
我不清楚类表达式和类声明.请帮助我了解它们之间的区别.
I'm not clear about Class expressions and Class declarations. Please help me to understand for the different between them.
谢谢
推荐答案
它相对简单.
在类表达式"中,将类对象 NamedFoo
分配给名为 Foo
的变量,如下所示:
In "Class Expressions", the class object NamedFoo
is being assigned to a variable named Foo
, like so:
var Foo = class NamedFoo {
constructor() {}
whoIsThere() {
return NamedFoo.name;
}
}
在类声明"中,类对象 NamedFoo
仅由其自身声明,如下所示:
In "Class Declarations", the class object NamedFoo
is being declared solely by itself, like so:
class NamedFoo {
constructor() {}
whoIsThere() {
return NamedFoo.name;
}
}
这里的区别还在于,当它是类声明"时,您可以使用 NamedFoo
引用该类,但是,当它是类表达式"时,您只能通过为其分配的变量(在本例中为 Foo
)引用该类.
The distinction here also being that when it's a "Class Declaration", you can reference the class by using NamedFoo
, however, when it's a "Class Expression", you'll only be able to reference the class by the variable that it was assigned to, in this case Foo
.
希望对您有帮助!
这篇关于ES6中的类声明和类表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!