欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

JavaScript 原型链与继承机制

时间:2026年08月12日 05:39:03 浏览:0

JavaScript 原型链与继承机制


原型链是 JavaScript 实现继承的核心机制。


1. 原型与 proto


function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' 叫了一声');
};
const dog = new Animal('旺财');
dog.speak(); // 旺财 叫了一声

2. 原型链



  • dog.__proto__ === Animal.prototype

  • Animal.prototype.__proto__ === Object.prototype

  • Object.prototype.__proto__ === null


3. 继承方式(ES6 class)


class Animal {
constructor(name) { this.name = name; }
speak() { console.log(this.name + ' 叫'); }
}
class Dog extends Animal {
bark() { console.log('汪汪'); }
}

4. 组合继承(原型链 + 构造函数)


function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

理解原型链有助于排查复杂继承问题。