js 实现类
在JavaScript中,可以通过多种方式实现类(class)的概念,以下是常见的几种方法:
构造函数模式
使用构造函数和new关键字创建对象实例。构造函数名通常首字母大写以区分普通函数。
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log(`Hello, ${this.name}`);
};
}
const person = new Person('Alice');
person.sayHello(); // 输出: Hello, Alice
原型链模式
通过原型(prototype)共享方法,避免每个实例重复创建方法,节省内存。
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, ${this.name}`);
};
const person = new Person('Bob');
person.sayHello(); // 输出: Hello, Bob
ES6 Class语法
ES6引入的class语法糖,更接近传统面向对象语言的写法,底层仍基于原型链。
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, ${this.name}`);
}
}
const person = new Person('Charlie');
person.sayHello(); // 输出: Hello, Charlie
工厂函数模式
不使用new关键字,通过函数直接返回对象,适合需要灵活控制对象创建的场景。
function createPerson(name) {
return {
name,
sayHello() {
console.log(`Hello, ${this.name}`);
}
};
}
const person = createPerson('Dana');
person.sayHello(); // 输出: Hello, Dana
静态方法与属性
通过static关键字定义类级别的属性和方法,无需实例化即可调用。
class MathUtils {
static PI = 3.14159;
static square(x) {
return x * x;
}
}
console.log(MathUtils.square(5)); // 输出: 25
继承实现
使用extends实现类继承,子类可通过super调用父类构造函数或方法。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
super.speak();
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // 输出: Rex makes a noise. Rex barks.
私有字段
ES2022引入的私有字段(以#开头),只能在类内部访问。
class Counter {
#count = 0;
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 输出: 1
注意事项
- 原型链方法适用于需要方法共享的场景,减少内存占用。
- ES6
class语法更清晰,但需注意它并非真正的类,而是语法糖。 - 工厂函数模式适合需要封装复杂对象创建逻辑的情况。
- 私有字段提供真正的封装性,但需注意浏览器兼容性。







