原型与原型链
每个函数都有 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 继承的核心,理解它有助于调试深层问题。
