JavaScript 中的类关键字


在 ES6 中引入的 JavaScript 类是 JavaScript 基于原型的继承中的语法糖。类实际上是“特殊函数”。你可以使用 class 关键字使用以下语法在 JavaScript 中定义类 -

class Person {
   // Constructor for this class
   constructor(name) {
      this.name = name;
   }
   // an instance method on this class
   displayName() {
      console.log(this.name)
   }
}

这本质上等效于以下声明 -

let Person = function(name) {
   this.name = name;
}
Person.prototype.displayName = function() {
   console.log(this.name)
}

这个类也可以写成类表达式。上述格式是类声明。以下格式是类表达式 -

// Unnamed expression
let Person = class {
   // Constructor for this class
   constructor(name) {
      this.name = name;
   }
   // an instance method on this class
   displayName() {
      console.log(this.name)
   }
}

无论你如何按上述方式定义类,都可以使用以下方式创建这些类的对象 -

示例

let John = new Person("John");
John.displayName();

输出

John

你可以在 https://tutorialspoint.com/es6/es6_classes.htm 上深入了解 JS 类和 class 关键字。

更新于:2019 年 9 月 18 日

160 次查看

开启您的职业生涯

完成课程,获得认证

开始
广告