欢迎来到程序员中文网!

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

JavaScript 原型链与继承机制

时间:2026年08月12日 04:50:02 浏览:0

原型与原型链


每个函数都有 prototype 属性,实例通过 __proto__ 链接到构造函数的原型。


function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' 叫了一声');
};

const dog = new Animal('旺财');
dog.speak(); // 旺财 叫了一声

console.log(dog.__proto__ === Animal.prototype); // true
console.log(Animal.prototype.__proto__ === Object.prototype); // true

继承方式


原型链继承


function Dog(name) {
Animal.call(this, name); // 借用构造函数
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log('汪汪');
};

ES6 class 语法


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

class Dog extends Animal {
bark() { console.log('汪汪'); }
}

原型是 JavaScript 继承的核心,理解它有助于调试深层问题。