JavaScript的OOP基于原型链而非类,对象通过[[Prototype]]指向原型,属性查找沿原型链向上搜索;构造函数配合new操作符创建实例,内部自动绑定this并返回新对象;继承可通过组合构造函数和Object.create(父原型)实现,或使用class与extends语法糖;封装早期依赖闭包模拟私有变量,ES2022引入#前缀实现真正私有字段。

JavaScript的面向对象编程(OOP)与其他语言不同,它基于原型(prototype)而非类(class)来实现对象和继承。虽然ES6引入了class语法糖,但底层机制依然是原型链。理解这些核心概念,才能真正掌握JavaScript中的OOP精髓。
每个JavaScript对象都有一个内部属性[[Prototype]],指向其原型对象。这个原型对象可以包含可被继承的方法和属性。
当你访问一个对象的属性或方法时,JavaScript引擎会先在该对象自身查找,如果找不到,就沿着原型链向上查找,直到找到或到达原型链末端(null)。
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
const alice = new Person("Alice");
console.log(alice.greet()); // "Hello, I'm Alice"
这里,alice自身没有greet方法,但它通过__proto__(即[[Prototype]])访问到Person.prototype上的方法。
立即学习“Java免费学习笔记(深入)”;
构造函数是普通函数,约定首字母大写,通过new调用。它会自动完成以下几步:
this绑定到该对象这是实现对象实例化的基本方式。即使使用class语法,底层依然依赖构造函数。
class Animal {
constructor(type) {
this.type = type;
}
speak() {
console.log(`${this.type} makes a sound`);
}
}
const dog = new Animal("Dog");
dog.speak(); // "Dog makes a sound"
这段代码等价于使用构造函数和原型手动定义。
JavaScript支持多种继承模式,最常见的是组合构造函数和原型链。
子类需要调用父类构造函数,并正确设置原型链。
经典组合继承:function Dog(name, breed) {
Person.call(this, name); // 继承属性
this.breed = breed;
}
Dog.prototype = Object.create(Person.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
return "Woof!";
};
这样,Dog实例既能访问Person的方法,也有自己的扩展。
现代写法中,class配合extends和super更简洁:
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
bark() {
console.log("Woof!");
}
}
传统JavaScript没有真正的私有字段,但可通过闭包模拟:
function Counter() {
let count = 0; // 私有变量
this.increment = function() {
count++;
};
this.getCount = function() {
return count;
};
}
ES2022引入了#语法支持真正私有字段:
class Counter {
#count = 0;
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
这避免了外部意外访问,提升封装性。
基本上就这些。掌握原型机制、构造函数、继承模式和封装手段,就能灵活运用JavaScript的面向对象能力。不复杂,但容易忽略细节。
以上就是JavaScript面向对象编程精髓的详细内容,更多请关注php中文网其它相关文章!
编程怎么学习?编程怎么入门?编程在哪学?编程怎么学才快?不用担心,这里为大家提供了编程速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号