深入ES6的 Class 类

108 阅读2分钟

浅谈 js 创建多个对象

1. 工厂函数

function createObj(name, age) {
    const obj = {};
    obj.name = name;
    obj.age = age;
    obj.sayHello = function() {
        console.log(`My name is ${this.namename}, I'm ${this.age} years old.`);
    }
    return obj;
}

const obj1 = createObj('curry', 20);
  • 缺点:创建出来的对象全是通过字面量创建的,获取不到对象真实的类型,皆为 object

2. 构造函数

function Person(name, age) { 
    this.name = name;
    this.age = age;
    this.sayHello = function() {
        console.log(`My name is ${this.name}, I'm ${this.age} years old.`);
    }
}
const p1 = new Person('curry', 30);
  • 缺点:每次 new 常见新对象时,会重新给每个对象创建新的属性,包括对象中方法,实际上,对象中的方法是可以共用的,消耗了不必要的内存

3. 原型 + 构造函数

function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.sayHello = function() {
    console.log(`My name is ${this.name}, I'm ${this.age} years old.`);
}

const p1 = new Person('curry', 30);
const p2 = new Person('kobe', 24);

console.log(p1.sayHello === p2.sayHello); // true

4. 使用类

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    sayHello() {
        console.log(`My name is ${this.name}, I'm ${this.age} years old.`);
    }
}
const p1 = new Person('curry', 30);

深入了解 Class 类

Class 类提供了一种更简洁、更清晰地定义对象和创建对象的方式,使得面向对象编程更加直观和易于理解

1. 简单 demo

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `Hello, my name is ${this.name} and I'm ${this.age} years old.`;
  }

  static description() {
    return 'This is a Person class.';
  }

  get fullName() {
    return this.name;
  }

  set fullName(value) {
    this.name = value;
  }
}

const person1 = new Person('Alice', 30);
console.log(person1.greet()); // 输出:Hello, my name is Alice and I'm 30 years old.
console.log(Person.description()); // 输出:This is a Person class.
// 可以直接对 name 进行访问和赋值
person1.name = 'demo';
console.log(person1.name);
  • 当通过new操作符来操作类时,就会去调用这个类的constructor方法,并返回一个对象
  • static 类的静态方法,直接类名调用
  • getset 是类的访问器方法

2. Class 的继承

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  study() {
    return `${this.name} is studying in grade ${this.grade}.`;
  }
}

const student1 = new Student('Bob', 15, 9);
console.log(student1.greet()); // 输出:Hello, my name is Bob and I'm 15 years old.
console.log(student1.study()); // 输出:Bob is studying in grade 9.
  • 使用super关键字可以在子类构造函数中调用父类的构造函数,但是必须在子类构造函数中使用this或者返回默认对象之前使用super