1. JavaScript面向对象编程核心概念解析
JavaScript作为一门多范式编程语言,其面向对象编程(OOP)能力经常被开发者低估。实际上,从ES5的原型继承到ES6的class语法糖,JavaScript提供了一套完整的OOP实现机制。理解这些概念对于构建可维护的大型应用至关重要。
注意:虽然ES6引入了class关键字,但JavaScript的OOP实现本质上仍是基于原型的,这与Java/C++等传统面向对象语言有显著区别。
1.1 对象与封装
在JavaScript中,对象是属性的集合,每个属性包含一个键值对。封装意味着将数据和行为捆绑在一起,并控制其可见性:
javascript复制// 对象字面量创建方式
const student = {
// 数据属性
_name: '张三', // 下划线约定表示私有
grade: 3,
// 方法
introduce() {
return `我是${this._name},${this.grade}年级学生`;
},
// Getter/Setter实现封装
get name() {
return this._name;
},
set name(value) {
if (value.length < 2) {
throw new Error('姓名过短');
}
this._name = value;
}
};
真正的私有属性需要使用ES2022的#语法或WeakMap实现:
javascript复制class Student {
#privateField; // 真正的私有字段
constructor(name) {
this.#privateField = name;
}
}
1.2 构造函数与原型链
JavaScript使用原型链实现继承,每个构造函数都有prototype属性,实例通过__proto__访问原型:
javascript复制function Person(name) {
this.name = name;
}
Person.prototype.introduce = function() {
console.log(`你好,我是${this.name}`);
};
function Student(name, grade) {
Person.call(this, name); // 调用父类构造函数
this.grade = grade;
}
// 设置原型链
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
const s = new Student('李四', 2);
s.introduce(); // 继承自Person原型
关键点:Object.create比直接赋值(Student.prototype = Pe
