发布于 2026-01-06 4 阅读
0

A Quick Guide to Get Started with JavaScript Classes

JavaScript 类入门快速指南

JavaScript 类是 JavaScript 的一个热门特性。本教程将帮助你学习使用 JavaScript 类所需的基本知识。你将学习类构造函数、属性和方法,以及公共、静态和私有类字段的概念。

简要介绍

在深入探讨如何开始使用 JavaScript 类之前,我们先快速了解一些基本概念。首先,类是在 ES6 规范(ECMAScript 2015)中引入 JavaScript 的。其次,类本身并不是一个全新的特性。类本质上提供了一种不同的对象创建方式,并支持原型和继承。

这也是为什么许多 JavaScript 开发者称类为语法糖的原因。他们的说法没错。类确实是一种语法糖。本质上,你仍然在使用对象、原型等等。唯一的真正区别在于你使用的语法。另一个区别是,你的代码在 IE 浏览器中无法运行。Babel可以帮助你解决这个问题。

也就是说,使用 JavaScript 类而不是其他旧方法并没有什么错。这主要取决于你的个人偏好。如果你喜欢,就用;如果你不喜欢,就不用。现在,让我们来看看你需要了解哪些内容才能开始使用 JavaScript 类。

语法

类的语法简单易学,也容易记忆。每个类都以class关键字开头。接下来是类体,也就是用花括号括起来的代码块。这里没有函数中常见的圆括号和参数。声明新类时,约定以大写字母开头。

// Create new class called "MyClass":
class MyClass {
  // Body of the class.
}
Enter fullscreen mode Exit fullscreen mode

类、构造函数和参数

声明新类时,没有括号可以用来指定参数。但这并不意味着类不支持参数。类支持参数,只是处理参数的方式不同。要为类指定参数,必须使用名为 `.` 的方法constructor

constructor是一个独特的方法。你只能在类内部创建它,而且只能创建一次。如果你不自己创建这个方法,JavaScript 会自动使用每个类内置的默认方法。这个方法的主要作用是执行你在创建类的新实例时指定的任务。

实例本质上是基于特定类的新对象,它继承了该类中定义的所有属性和方法。每次创建类的新实例时,都会自动调用相应的constructor方法。这在创建新类实例时非常有用。

例如,constructor可以为属性赋予初始值。此外,还可以指定参数。该constructor方法是一个普通方法,因此也可以接受参数。如果为该constructor方法指定了参数,这些参数将成为类本身的参数。

创建类的新实例时,您可以根据 `__init__` 方法的参数传递一些值作为参数constructor。否则,您可以省略所有参数,仅使用 `__init__` 方法constructor执行一些初始任务。如果您定义了自己的 ` constructor__init__` 方法并替换了默认值,请在类的顶部进行相应的修改。

// Create new class "MyClass" with constructor,
// but without any parameters.
class MyClass {
  // Create constructor method without any parameters
  constructor() {
    // Code that will be executed
    // when a new class instance is created.
  }
}


// Create new class "MyClass"
// that accepts two parameters: name and age.
class MyClass {
  // Create constructor method
  // and specify "name" and "age" parameters.
  constructor(name, age) {
    // Create properties "name" and "age" on the class
    // and assign them values passed as arguments
    // for "name" and "age" parameters.
    this.name = name
    this.age = age
  }
}
Enter fullscreen mode Exit fullscreen mode

这和课程

在处理 JavaScript 类时,你很可能会频繁地看到`this` 关键字。基本上,你只需要记住这一点:在this类内部使用 `this` 时,它指向类本身;创建该类的新实例时,它指向的正是你创建的这个实例。

运用想象力可以帮助你。当你看到this一个类的内部结构时,你可以想象把它替换this成你当前正在处理的类的名称。理论上来说,这就是实际发生的情况。

// Create new class:
class MyClass {
  // Create constructor and define one parameter:
  constructor(name) {
    // This:
    this.name = name
    // Can be translated here to:
    // MyClass.name = name

    // When you create an instance of MyClass
    // it can be translated here to:
    // InstanceOfMyClass.name = name
  }
}
Enter fullscreen mode Exit fullscreen mode

类属性和方法

就像任何对象一样,每个类都可以拥有无​​限多个属性。最初,定义这些属性只有一种方法:只能在方法内部定义属性。需要注意的是,方法是否接受参数constructor并不重要。constructor

即使该constructor方法不接受任何参数,定义类属性仍然只能在该方法内部进行。这种情况只是有所改变。该constructor方法仍然是定义类参数并将其值赋给某些类属性的唯一途径。

// Create new class:
class MyClass {
  // Create constructor and define one parameter:
  constructor(name) {
    // Create class property called "name"
    // and assign it a value of "name" parameter
    this.name = name

    // Create additional class properties:
    this isHuman = true
    this.isAlive = true
  }
}
Enter fullscreen mode Exit fullscreen mode

创建类属性的另一种方法是使用类字段。类字段和类属性的名称几乎相同。区别在于,属性定义在constructor方法内部,而类字段定义在方法外部,即类体内部。除此之外,类属性和类字段基本上可以互换使用。

目前,类字段分为三种类型:公共字段、静态字段和私有字段。我们将在下一节中逐一讨论。但首先,让我们快速了解一下类方法。

类方法

创建类方法时,直接在类体内部定义即可。定义类方法和定义函数一样简单,区别在于:创建类方法时,无需使用 `method` 关键字,直接写方法名即可。而且,定义方法时function也不需要 ` method` 关键字。this

但是,如果您想引用正在操作的类的某个属性或方法,就需要用到实例this。当您想要调用某个类方法时,需要创建一个类的新实例。然后,使用点号表示法在该实例上调用该方法。

// Create new class with method:
class MyClass {
  // Create class method:
  myMethod() {
    return 'Hello!'
  }
}

// Create instance of "MyClass":
const myClassInstance = new MyClass()

// Call "myMethod" on "myClassInstance" instance:
joe.myMethod()
// Output:
// 'Hello!'


// Create new class with method using this:
class MyClass {
  // Create constructor and define one parameter:
  constructor(name) {
    // Create class property called "name"
    // and assign it a value of "name" parameter
    this.name = name
  }

  // Create class method:
  sayHi() {
    return `Hello, my name is ${this.name}.`
  }
}

// Create instance of "MyClass":
const joe = new MyClass('Joe')

// Call "sayHi" on "joe" instance:
joe.sayHi()
// Output:
// 'Hello, my name is Joe.'
Enter fullscreen mode Exit fullscreen mode

公共类字段和方法

类属性和公共类字段非常相似。主要区别在于,类属性是在constructor方法内部定义的。而类字段不需要 `@class`,constructor因为它们是在方法外部定义的。这也意味着,如果不需要 `@class` 用于constructor其他用途,则可以省略它。

但是,如果您想定义类参数或在类实例化期间执行某些操作,仍然需要使用 `public`关键字constructor。另一个重要的区别是,公共字段不使用 ` thispublic` 关键字。定义新的公共字段时,您需要以字段(属性)的名称开头,而不是以 `public`this和 `.` 开头。

关于公共类字段及其访问权限,有一点需要注意。您定义为公共的字段始终可以从类的内部和外部以及类的实例访问。这意味着您可以根据需要访问和修改它们。公共方法也是如此。它们都可以访问和修改。

最后一点。默认情况下,你定义的任何类字段和方法都是公共的。你可以通过将字段或方法定义为静态或私有来更改其默认行为。这意味着使用相应的关键字。否则,JavaScript 会自动假定字段或方法应该是公共的,并将其设置为公共。

// Create new class:
class Car {
  // Define class fields for "numOfWheels" and "fuel":
  numOfWheels = 4
  fuelType = 'electric'

  // Define public method:
  startEngine() {
    return 'Engine is running.'
  }
}

// Create instance of Car class:
const tesla = new Car()

// Log the value of public class field "fuelType":
console.log(tesla.fuelType)
// Output:
// 'electric'

// Call the "startEngine" method:
console.log(tesla.startEngine())
// Output:
// 'Engine is running.'
Enter fullscreen mode Exit fullscreen mode

静态类字段和方法

第二类字段和方法是静态的。要定义静态类字段或方法,需要static在字段或方法名称前添加关键字 `static`。静态类字段和公共类字段的主要区别在于,你无法在类的实例上访问静态类字段。

静态类字段只能在类本身上访问。静态方法也一样,不能在类的实例上调用。静态字段和方法通常用于实用目的,例如清理、更新或记录现有类实例的信息。

使用静态类字段时,请记住只有静态方法才能访问它们。您不能使用公共方法或私有方法访问静态类字段,只能使用静态方法。

class Car {
  // Declare static property to keep track
  // of how many instances of Car has been created.
  static numOfCopies = 0

  constructor() {
    // When new instance of Car is created
    // update the number of Car instances:
    Car.numOfCopies++
  }

  // Create static method to access
  // static field "numOfCopies".
  static getNumOfCopies() {
    // Return the value of "numOfCopies" field:
    return Car.numOfCopies
  }
}

// Log number of instances of MyClass
console.log(Car.getNumOfCopies())
// Output:
// 0

// Create instance of Car:
const porsche = new Car()

// Log number of instances of Car again:
console.log(Car.getNumOfCopies())
// Output:
// 1
Enter fullscreen mode Exit fullscreen mode

私有类字段和方法

私有类字段和方法是您可以使用的最后一种字段和方法类型。私有类字段和方法与公共字段和方法基本相反。当您将某个字段或方法定义为私有时,您只能在类内部使用它。从外部来看,它们是不可见的。

当您需要将某些数据设为私有时,此功能非常有用。例如,您希望某些数据无法从外部或任何类实例访问。私有字段和方法的语法很简单。要定义私有字段或方法,只需在名称前加上#井号 (#) 即可。

当你想访问私有字段或调用私有方法时,也需要使用井号(#)。有趣的是,公共方法可以访问私有字段和方法。所以,如果你愿意,可以先创建一个私有字段或方法,然后再创建一个公共方法来访问或调用该私有方法。这两种方法都可行。

class App {
  // Declare private field "version":
  #version = '1.0'

  // Create private method "getVersion":
  #getVersion() {
    return this.#version
  }

  // Create public method "getVersionPublic" to access
  // private field "version":
  getVersionPublic() {
    // Return the value of "numOfCopies" field:
    return this.#version
  }

  // Create another public method "callGetVersion"
  // that calls the private method "getVersion":
  callGetVersion() {
    return this.#getVersion()
  }
}

// Create instance of Car:
const myApp = new App()

// Log number of instances of Car again:
console.log(myApp.getVersionPublic())
// Output:
// '1.0'

console.log(myApp.callGetVersion())
// Output:
// '1.0'
Enter fullscreen mode Exit fullscreen mode

类和实例

我们之前已经多次讨论过类的实例,现在是时候更深入地探讨一下了。正如我之前提到的,实例就像是基于现有类创建的新对象。创建新实例的原因在于,它们会自动继承你在其所基于的类中定义的属性和方法。

这意味着,如果您想在多个对象中使用相同的代码,不必一遍又一遍地编写。您可以创建一个类,并将需要重用的代码放在其中。当您需要一个能够执行所有这些操作的对象时,可以使用该类创建新实例。

这个实例将继承你在“父”类中定义的属性和方法。它将能够使用这些属性和方法。要创建类的新实例,你需要声明一个新变量。在右侧,使用关键字 `new`,new后跟要实例化的类的名称,并用括号括起来。

如果类接受参数,则将参数放在类名后面的括号内。否则,括号留空。这样,您可以创建任意数量的同一类的实例。

请记住,您在特定类中“硬编码”的所有属性及其值constructor都将被该类的所有实例继承。任何您通过参数传递的值都将是动态的,它们取决于您在实例化过程中使用的参数。

// Class without parameters:
class MyClass {
  // Create constructor:
  constructor() {
    // Create class property "isAlive" and assign it true.
    this.isAlive = true
  }
}

// Create instance of "MyClass" class:
const myClassInstance = new MyClass('Jessica')

// log the value of "isAlive" property
// on "myClassInstance" instance:
console.log(myClassInstance.isAlive)
// Output:
// true


// Class with one parameter:
class MyClassTwo {
  // Create constructor and define one parameter:
  constructor(name) {
    // Create class property called "name"
    // and assign it a value of "name" parameter
    // and another boolean property "isAlive".
    this.name = name
    this.isAlive = true
  }
}

// Create instance of "MyClassTwo" class
// and pass in argument for "name" parameter:
const myClassInstanceTwo = new MyClassTwo('Jacob')

// log the value of "name" property
// on "myClassInstanceTwo" instance:
console.log(myClassInstanceTwo.name)
// Output:
// 'Jacob'

// Create another instance of "MyClassTwo" class
const myClassInstanceThree = new MyClassTwo('Tobias')

// log the value of "name" property
// on "myClassInstanceTwo" instance:
console.log(myClassInstanceThree.name)
// Output:
// 'Tobias'
Enter fullscreen mode Exit fullscreen mode

结论:JavaScript 类入门快速指南

JavaScript 类是一个很有意思的特性,它提供了一种创建对象、使用原型和原型继承的新方式。希望这篇简短的指南能帮助你理解一些基础知识,以便你开始使用 JavaScript 类。

如果您觉得 JavaScript 类很有趣,并且想了解更多,请查看《JavaScript 类——友好入门(第一部分)》和《JavaScript 类——友好入门(第二部分)》。这两篇教程将为您提供更深入的 JavaScript 类信息,并补充本简短指南中可能略过的内容。

文章来源:https://dev.to/alexdevero/a-quick-guide-to-get-started-with-javascript-classes-2033