constructor = special method for defining the properties and methods of objects

  • 构造函数 是用来 创建对象 的特殊函数。
  • 它的作用就是当你 new 一个对象时,帮你初始化这个对象的 属性方法
function car(make, model, year, color){
    // this → 指向新创建的对象
    this.make = make; // 品牌
    this.model = model; // 型号
    this.year = year; // 年份
    this.color = color; // 颜色
    
    this.drive = function(){ // 方法
        console.log(`you are driving ${this.year},${this.model}`)}
}
 
// 使用 new 关键字来实例化对象
const car1 = new car("Ford","Mustang",2024,"Yellow");
const car2 = new car("AlfaRomeo","Giulia",2024,"Black")
const car3 = new car("Ferrari","SF90",2020,"Red")
 
// 把对象放进数组里
const cars = [car1, car2, car3];
 
console.log(cars);  // 打印所有车对象
cars[1].drive();  // "you are driving 2024,Giulia"

output:

[
  car {
    make: 'Ford',
    model: 'Mustang',
    year: 2024,
    color: 'Yellow',
    drive: [Function (anonymous)]
  },
  car {
    make: 'AlfaRomeo',
    model: 'Giulia',
    year: 2024,
    color: 'Black',
    drive: [Function (anonymous)]
  },
  car {
    make: 'Ferrari',
    model: 'SF90',
    year: 2020,
    color: 'Red',
    drive: [Function (anonymous)]
  }
]
you are driving 2024,Giulia

=== Code Execution Successful ===

构造函数 vs class

构造函数写法

function Car(make, model, year, color){
    this.make = make;
    this.model = model;
    this.year = year;
    this.color = color;
    this.drive = function(){
        console.log(`you are driving ${this.year},${this.model}`);
    }
}

class 写法

class Car {
    constructor(make, model, year, color){
        this.make = make;
        this.model = model;
        this.year = year;
        this.color = color;
    }
    drive(){
        console.log(`you are driving ${this.year},${this.model}`);
    }
}

效果是一样的,只是 class 更清晰、更符合现代语法习惯。