在 JavaScript 早期,使用函数和原型链实现面向对象的思想,语法复杂且容易出错。引入 class 后,语法更加直观。
2. 类(class)与构造函数(constructor)
2.1 类的基本语法
class 是用来定义对象蓝图的关键字,其中包含对象的属性和方法。
classPerson{// 构造函数:定义对象的初始化逻辑constructor(name, age){this.name = name;// this 代表当前实例this.age = age;}// 定义实例方法sayHello(){
console.log(`Hello, my name is ${this.name}.`);}}// 创建类的实例const person1 =newPerson("Kevin",25);
console.log(person1.name);// 输出:Kevin
person1.sayHello();// 输出:Hello, my name is Kevin.
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">
classAnimal{constructor(name){this.name = name;}makeSound(){
console.log(`${this.name} is making a sound.`);}}classDogextendsAnimal{constructor(name, breed){super(name);// 调用父类的构造函数this.breed = breed;}makeSound(){
console.log(`${this.name}, a ${this.breed}, barks.`);}}const dog =newDog("Buddy","Golden Retriever");
dog.makeSound();// 输出:Buddy, a Golden Retriever, barks.
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">
classAnimal{makeSound(){
console.log("Animal is making a sound.");}}classDogextendsAnimal{makeSound(){
console.log("Dog is barking.");}}classCatextendsAnimal{makeSound(){
console.log("Cat is meowing.");}}const animals =[newDog(),newCat()];
animals.forEach(animal=> animal.makeSound());// 输出:// Dog is barking.// Cat is meowing.
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"> class="hide-preCode-box">
评论记录:
回复评论: