A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/class below:

类表达式 - JavaScript | MDN

类表达式

Baseline Widely available

class 关键字可用于在表达式中定义类。类似于函数表达式,类表达式可以是命名的,也可以是匿名的。如果命名,则类的名称只能在类体内部才能访问到。

尝试一下
const Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  area() {
    return this.height * this.width;
  }
};

console.log(new Rectangle(5, 8).area());
// Expected output: 40
语法
const MyClass = class [className] [extends otherClassName] {
  // class body
}
描述

类表达式的语法类似于类声明。与 class 声明一样,class 表达式的主体在严格模式下执行。

类表达式和类声明之间存在一些差异,但是:

constructor 方法是可选的。使用类表达式生成的类将始终响应 typeof 值为 "function"。

"use strict";
let Foo = class {}; // constructor property is optional
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 SyntaxError (class declarations do not allow re-declaration)
示例 一个简单的类表达式

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

const Foo = class {
  constructor() {}
  bar() {
    return "Hello World!";
  }
};

const instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"
命名类表达式

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

const Foo = class NamedFoo {
  constructor() {}
  whoIsThere() {
    return NamedFoo.name;
  }
};
const bar = new Foo();
bar.whoIsThere(); // "NamedFoo"
NamedFoo.name; // ReferenceError: NamedFoo is not defined
Foo.name; // "NamedFoo"
规范 浏览器兼容性 参见

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4