JavaScript面向对象基于原型机制,ES6的class只是构造函数+prototype的语法糖;核心在于掌握原型链、构造函数、继承及封装(如#私有字段)。

JavaScript 实现面向对象编程(OOP)不依赖传统类语法(早期版本),而是基于原型(prototype)机制。ES6 引入 class 关键字,但本质仍是原型的语法糖。掌握原型、构造函数、继承和封装逻辑,才是理解 JS 面向对象的关键。
用构造函数 + prototype 模拟类
这是最贴近“类”思想的原始方式:构造函数定义实例属性,prototype 上挂载共享方法,避免重复创建函数。
例如:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
return `Hello, I'm ${this.name}`;
};
const p1 = new Person('Alice', 25);
p1.sayHello(); // "Hello, I'm Alice"
用 class 语法(ES6+)更简洁地组织代码
class 不是新机制,只是对构造函数 + prototype 的封装,写法更直观,支持 static、getter/setter、extends 等特性。
立即学习“Java免费学习笔记(深入)”;
例如:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
static isAlive() { // 静态方法,属于类本身
return true;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 调用父类构造器
this.breed = breed;
}
speak() {
return `${this.name} barks!`;
}
}
const dog = new Dog('Buddy', 'Golden');
dog.speak(); // "Buddy barks!"
Animal.isAlive(); // true
实现封装与私有成员(现代推荐方式)
JS 原生不支持 private 关键字(直到 ES2022 才有 #field 私有字段),但可通过以下方式控制访问:
标签: javascript es6 java js go 面向对象编程 speak
还木有评论哦,快来抢沙发吧~