首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

class

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

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

语法

代码语言:javascript
复制
var MyClass = class [className] [extends] {
  // class body
};

描述

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

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

代码语言:javascript
复制
'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”来引用它。

代码语言:javascript
复制
var Foo = class {
  constructor() {}
  bar() {
    return 'Hello World!';
  }
};

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

命名的类表达式

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

代码语言:javascript
复制
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

扫码关注腾讯云开发者

领取腾讯云代金券