JavaScript 类
类是对象的蓝图,提供了一种更正式、更组织化的方式来定义对象及其行为。JavaScript 类并非对象本身,而是创建 JavaScript 对象的模板。
类是一种特殊的函数,但我们使用关键字 class
来定义它,而不是 function
。属性在 constructor()
方法内部赋值。
类方法
class
关键字创建类。constructor()
方法。示例 1:创建汽车类,然后基于汽车类创建一个名为“我的车”的对象。
class Car { constructor(brand) { this.carName = brand; } } let myCar = new Car("Toyota");
构造函数方法
构造函数是一种特殊的方法,用于初始化用类创建的对象。在创建类的新的实例时,它会自动调用。它通常使用传递给它的参数为对象属性赋值,确保对象在创建时正确初始化。
当构造函数自动调用且类被初始化时,它必须具有确切的名称“constructor”。事实上,如果您没有构造函数,JavaScript 将添加一个不可见的空构造函数方法。
注意:一个类不能有多个 constructor()
方法,这将引发语法错误。
更多类示例
class Person {} // 空类 class Student { constructor(rollNo, name, age) { this.name = name; this.rollNo = rollNo; this.age = age; } } let student1 = new Student(1, "Alex", 12); console.log(student1); // Output: Student { name: 'Alex', rollNo: 1, age: 12 } class Product { constructor(name, price) { this.name = name; this.price = price; } displayProduct() { console.log(`Product: ${this.name}`); console.log(`Price: ${this.price}`); } } const product1 = new Product("Shirt", 19.32); const product2 = new Product("Pant", 33.55);
以上是JavaScript 中的类的详细内容。更多信息请关注PHP中文网其他相关文章!