在JavaScript中,类是特殊的函数类型。无涯教程可以像函数声明和函数表达式一样定义类。
JavaScript类在包含方法或构造函数的主体中包含各种类成员。该类以严格模式执行。因此,包含无提示错误或错误的代码将引发错误。
类语法包含两个组件:
可以通过使用类声明来定义类。 class关键字用于声明具有任何特定名称的类。根据JavaScript的命名约定,类的名称始终以大写字母开头。
看一个简单的声明类的例子。
<script> //Declaring class class Employee { //Initializing an object constructor(id,name) { this.id=id; this.name=name; } //Declaring method detail() { document.writeln(this.id+" "+this.name+"<br>") } } //passing object to a variable var e1=new Employee(101,"Martin Roy"); var e2=new Employee(102,"Duke William"); e1.detail(); //calling method e2.detail(); </script>
输出:
101 Martin Roy 102 Duke William
与函数声明不同,类声明不是JavaScript提升的一部分。因此,需要在调用它之前声明该类。
来看一个例子。
<script> //Here, we are invoking the class before declaring it. var e1=new Employee(101,"Martin Roy"); var e2=new Employee(102,"Duke William"); e1.detail(); //calling method e2.detail(); //Declaring class class Employee { //Initializing an object constructor(id,name) { this.id=id; this.name=name; } detail() { document.writeln(this.id+" "+this.name+"<br>") } } </script>
输出:
一个类只能声明一次。如果尝试多次声明类,则会引发错误。来看一个例子。
<script> //Declaring class class Employee { //Initializing an object constructor(id,name) { this.id=id; this.name=name; } detail() { document.writeln(this.id+" "+this.name+"<br>") } } //passing object to a variable var e1=new Employee(101,"Martin Roy"); var e2=new Employee(102,"Duke William"); e1.detail(); //calling method e2.detail(); //Re-declaring class class Employee { } </script>
输出:
定义类的另一种方法是使用类表达式。在此,不必强制分配类的名称。因此,可以对类表达式进行命名或未命名。类表达式允许无涯教程获取类名称。但是,使用类声明是不可能的。
可以在不为其指定任何名称的情况下表示该类。来看一个例子。
<script> var emp = class { constructor(id, name) { this.id = id; this.name = name; } }; document.writeln(emp.name); </script>
输出:
emp
与类声明不同,类表达式可以重新声明同一类。因此,如果尝试多次声明该类,则会引发错误。
<script> //Declaring class var emp=class { //Initializing an object constructor(id,name) { this.id=id; this.name=name; } //Declaring method detail() { document.writeln(this.id+" "+this.name+"<br>") } } //passing object to a variable var e1=new emp(101,"Martin Roy"); var e2=new emp(102,"Duke William"); e1.detail(); //calling method e2.detail(); //Re-declaring class var emp=class { //Initializing an object constructor(id,name) { this.id=id; this.name=name; } detail() { document.writeln(this.id+" "+this.name+"<br>") } } //passing object to a variable var e1=new emp(103,"James Bella"); var e2=new emp(104,"Nick Johnson"); e1.detail(); //calling method e2.detail(); </script>
输出:
101 Martin Roy 102 Duke William 103 James Bella 104 Nick Johnson
可以用特定的名称来表示该类。在此,类名称的范围取决于类主体。使用class.name属性检索该类。
<script> var emp = class Employee { constructor(id, name) { this.id = id; this.name = name; } }; document.writeln(emp.name); /*document.writeln(Employee.name); Error occurs on console: "ReferenceError: Employee is not defined */ </script>
输出:
Employee
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)