非常教程

JavaScript参考手册

Operators

class

class 声明创建一个基于原型继承的具有给定名称的新类。

你也可以使用类表达式定义类。但是不同于类表达式,类声明不允许再次声明已经存在的类,否则将会抛出一个类型错误。

语法

var MyClass = class [className] [extends] {
  // class body
};

描述

类表达式与类声明(声明)具有类似的语法。但是,对于类表达式,您可以省略类名(“绑定标识符”),而不能使用类语句。此外,类表达式允许您重新定义/重新声明类,不要抛出任何类型错误,如类声明。构造函数属性是可选的。而且,typeof运算使用此关键字生成的类将永远是“功能”。

就像使用类语句一样,类表达式的类体以严格模式执行。

'use strict';
var Foo = class {}; // constructor property is optional
var Foo = class {}; // Re-declaration is allowed

typeof Foo; //returns "function"
typeof class {}; //returns "function"

Foo instanceof Object; // true
Foo instanceof Function; // true
class Foo {}; // Throws TypeError, doesn't allow re-declaration

示例

简单类表达式

这只是一个简单的匿名类表达式,您可以使用变量“Foo”来引用它。

var Foo = class {
  constructor() {}
  bar() {
    return 'Hello World!';
  }
};

var instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"

命名的类表达式

如果要引用类体内的当前类,则可以创建一个已命名的类表达式。该名称仅在类表达式本身的范围内可见。

var Foo = class NamedFoo {
  constructor() {}
  whoIsThere() {
    return NamedFoo.name;
  }
}
var bar = new Foo();
bar.whoIsThere(); // "NamedFoo"
NamedFoo.name; // ReferenceError: NamedFoo is not defined
Foo.name; // "NamedFoo"

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Class definitions' in that specification.

Standard

Initial definition.

ECMAScript 2016 (ECMA-262)The definition of 'Class definitions' in that specification.

Standard

ECMAScript 2017 (ECMA-262)The definition of 'Class definitions' in that specification.

Standard

ECMAScript Latest Draft (ECMA-262)The definition of 'Class definitions' in that specification.

Living Standard

浏览器兼容性

Feature

Chrome

Edge

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

42.0

(Yes)

45 (45)

?

?

?

Feature

Android

Android Webview

Edge

Firefox Mobile (Gecko)

IE Mobile

Opera Mobile

Safari Mobile

Chrome for Android

Basic support

No support

42.0

(Yes)

45.0 (45)

?

?

?

42.0

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络