Javascript 简明教程
JavaScript - Classes
JavaScript Classes
JavaScript classes 是对象创建的蓝图或模板。它们封装了数据和操作该数据的函数。我们可以使用类创建对象。从类创建对象称为实例化类。在 JavaScript 中,类建立在原型之上。类在 2009 年的 ECMAScript 6 (ES6) 中被引入 JavaScript。
The JavaScript classes are a blueprint or template for object creation. They encapsulate the data and functions to manipulate that data. We can create the object using classes. Creating an object from a class is referred to as instantiating the class. In JavaScript, the classes are built on prototypes. The classes are introduced to JavaScript in ECMAScript 6 (ES6) in 2009.
例如,你可以考虑编写代码来表示汽车实体。代码可以包含具有汽车属性的类。对于不同的汽车,你可以创建类的实例,并根据汽车型号初始化汽车属性。
For example, you can think about writing code to represent the car entity. A code can contain the class having car properties. For different cars, you can create an instance of the class and initialize the car properties according to the car model.
在 ES6 之前,构造函数用于定义对象的蓝图。你可以按如下所示定义构造函数。
Before ES6, the constructor function was used to define a blueprint of the object. You can define the constructor function as shown below.
function Car(brand) { // Constructor function
this.brand = brand; // property initialization
}
const carObj = new Car("Audi"); // Creating an object
Defining JavaScript Classes
类的语法与构造函数非常相似,但它使用“class”关键字定义类。由于我们可以使用函数声明或函数表达式定义函数,所以也可以使用类声明或类表达式定义类。
The syntax of the class is very similar to the constructor function, but it uses the 'class' keyword to define the class. As we can define a function using function declaration or function expression, the classes are also can be defined using class declaration or class expression.
Syntax
JavaScript 中的类定义语法如下:
The syntax of class definition in JavaScript is as follows −
// class declaration
class ClassName {
// Class body
}
//Class expression
const ClassName = class {
// class body
}
在上面的语法中,“ClassName”是类名。
A 'ClassName' is a class name in the above syntax.
JavaScript 类是一个函数,但你不能将其用作常规函数。
A JavaScript class is a function, but you can’t use it as a regular function.
Type of JavaScript Classes
JavaScript 类是一种 function 。在下面的示例中,我们使用 'typeof' 运算符来获取类的类型。它返回 'function',您可以在输出中观察到。
A JavaScript class is a type of function. In the example below, we used the 'typeof' operator to get the type of the class. It returns the 'function’, which you can observe in the output.
<!DOCTYPE html>
<html>
<body>
<p id = "output"> The type of the car class is: </p>
<script>
class Car {
// Class body
}
document.getElementById("output").innerHTML += typeof Car;
</script>
</body>
</html>
The type of the car class is: function
The constructor() method
当您使用该函数作为对象蓝图时,可以在函数体内部初始化对象属性。类似地,您需要对该类使用 constructor() 方法来初始化对象属性。
When you use the function as an object blueprint, you can initialize the object properties inside the function body. Similarly, you need to use the constructor() method with the class to initialize the object properties.
无论何时创建该类的实例,它都会自动调用该类的 constructor() 方法。
Whenever you create an instance of the class, it automatically invokes the constructor() method of the class.
在下面的示例中,我们使用 constructor() 方法创建一个 Car 类 −
In below example, we use the constructor() method to create a Car class −
class Car {
constructor(brand) {// Defining the constructor
this.brand = brand;
}
}
constructor() 方法没有特定的名称,但可以使用 'constructor' 关键字创建。您可以在构造函数内部使用 'this' 关键字初始化类属性。
The constructor() method has no specific name but can be created using the 'constructor' keyword. You can initialize the class properties using the 'this' keyword inside the constructor function.
Creating JavaScript Objects
要创建 JavaScript 类的对象,我们使用 new 运算符,后跟类名称和一对括号。我们还可以向其传递三个参数。
To create an object of a JavaScript class, we use new operator followed by the class name and a pair of parentheses. We can pass thee arguments to it also.
我们按照以下方式创建一个名为 myCar 的对象 −
Let’s create an object called myCar as follows −
const myCar = new Car("Audi");
构造函数内部的 this 关键字指的是执行当前函数的对象。
The this keyword inside the constructor function refers to an object that is executing the current function.
Example: Creating class objects without arguments
在下面的示例中,我们定义了 'Car' 类。该类包含构造函数并使用默认值初始化属性。
In the example below, we have defined the 'Car' class. The class contains the constructor and initializes the properties with default values.
在此之后,我们创建该类的实例,您可以在输出中观察到它。
After that, we have created the instance of the class, and you can observe it in the output.
<!DOCTYPE html>
<html>
<body>
<p id = "output"> </p>
<script>
// creating Car class
class Car {
constructor() {
this.brand = "BMW";
this.model = "X5";
this.year = 2019;
}
}
// instantiate myCar object
const myCar = new Car();
// display the properties
document.getElementById("output").innerHTML =
"Car brand is : " + myCar.brand + "<br>"
+"Car model is : " + myCar.model + "<br>"
+"Car year is : " + myCar.year + "<br>";
</script>
</body>
</html>
Car brand is : BMW
Car model is : X5
Car year is : 2019
如果您希望动态初始化类属性,则可以使用 constructor() 方法的参数。
If you want to initialize the class properties dynamically, you can use the parameters with the constructor() method.
Example: Creating class objects with arguments
在下面的示例中,我们定义了 'Car' 类。该类的 constructor() 方法接收 4 个参数并使用参数值初始化类属性。
In the example below, we have defined the 'Car' class. The constructor() method of the class takes 4 parameters and initializes the class properties with parametric values.
在创建 'Car' 类实例时,我们传递了 4 个参数。通过这种方式,您可以动态初始化类属性。
While creating the 'Car' class instance, we passed 4 arguments. In this way, you can initialize the class properties dynamically.
<!DOCTYPE html>
<html>
<body>
<p id = "output"> </p>
<script>
class Car {
constructor(brand, model, price, year) {
this.brand = brand;
this.model = model;
this.price = price;
this.year = year;
}
}
const carObj = new Car("BMW", "X5", 9800000, 2019);
document.getElementById("output").innerHTML +=
"Car brand : " + carObj.brand + "<br>"
+ "Car model : " + carObj.model + "<br>"
+ "Car price : " + carObj.price + "<br>"
+ "Car year : " + carObj.year + "<br>"
</script>
</body>
</html>
Car brand : BMW
Car model : X5
Car price : 9800000
Car year : 2019
JavaScript Class Methods
您还可以在类内部定义方法,可以使用类实例访问这些方法。
You can also define the methods inside the class, which can be accessed using the class instance.
Syntax
按照以下语法在类内部定义方法。
Follow the syntax below to define methods inside the class.
class car {
methodName(params) {
// Method body
}
}
obj.methodName();
在上述语法中,'methodName' 是方法的动态名称。要定义类方法,您不需要在方法名前面编写任何关键字(如 'function')。
In the above syntax, 'methodName' is a dynamic name of the method. To define a class method, you don’t need to write any keyword like 'function' before the method name.
要调用类方法,您需要使用该类的实例。在此处,'obj' 是该类的实例。您还可以将参数传递给该方法。
To invoke the class method, you need to use the instance of the class. Here, 'obj' is an instance of the class. You can also pass the parameters to the method.
Example
下面的示例演示如何将参数传递给类方法。
The example below demonstrates how to pass parameters to the class methods.
在这里,我们定义了 updateprice() 方法来更新汽车的价格。因此,在调用 updateprice() 方法时,我们将新价格作为参数传递,并在方法体内使用它来更新价格。
Here, we have defined the updateprice() method to update the price of the car. So, while invoking the updateprice() method, we pass the new price as an argument and use it inside the method body to update the price.
在输出中你能看到汽车的原始价格和更新价格。
You can see the original and updated price of the car in the output.
<!DOCTYPE html>
<html>
<body>
<p id = "output"> </p>
<script>
class Car {
constructor(brand, model, price, year) {
this.brand = brand;
this.model = model;
this.price = price;
this.year = year;
}
updateprice(newPrice) {
this.price = newPrice;
}
}
const myCar = new Car("BMW", "X5", 9800000, 2019);
document.getElementById("output").innerHTML +=
"The car price is : " + myCar.price + "<br>";
myCar.updateprice(8800000); // updating price
document.getElementById("output").innerHTML +=
"After updating the car price is : " + myCar.price + "<br>";
</script>
</body>
</html>
The car price is : 9800000
After updating the car price is : 8800000
JavaScript Class Hoisting
在 JavaScript 中,类声明不会提升到代码开端。因此,你总是必须在使用前定义类。
In JavaScript, the declaration of the class is not hoisted at the top of the code. So, you always need to define the class before you use it.
const carObj = new Car(); // This will generate an error.
class Car {
}
你可以尝试运行上述代码。它会生成一个引用错误,因为汽车类在初始化前被使用了。
You can try to run the above code. It will generate a reference error as the car class is used before its initialization.
Strict Mode with Classes
严格模式用于避免异常错误。在默认情况下,类代码总是处于严格模式。
The strict mode is used to avoid unusual errors. The class code is always in the strict mode by default.
让我们通过以下示例了解它。
Let’s understand it via the example below.
class numbers {
constructor() {
num = 90; // Defining variable without var keyword
}
}
const numObj = new numbers();
在上述代码中,我们在 constructor() 方法中定义了 “num” 全局变量。在 strict 模式的 JavaScript 中,不允许在不使用 var、let 或 const 关键字的情况下定义变量。因此,上述代码将抛出一个错误。
In the above code, we define the 'num' global variable in the constructor() method. In the strict mode of JavaScript, it is not allowed to define the variables without using the var, let, or const keywords. So, the above code will throw an error.