原型是 JS 面向对象的底层,class 是它的现代语法糖。本文讲透原理与继承,结尾附动物类小案例。
一、原型三件套
function Person(name) { this.name = name; }
Person.prototype.hello = function () { return `hi ${this.name}`; };
const p = new Person('Tom');
p.hello(); // "hi Tom"(方法来自 prototype)
// 关系:
// p.__proto__ === Person.prototype true
// Person.prototype.__proto__ === Object.prototype
// p.constructor === Person
原型链查找:p.hello
1. p 自身有没有?没有
2. p.__proto__(Person.prototype)有没有?有 → 执行
3. 没有再往上 Object.prototype → null
二、new 的四步
new Person('Tom') 等价于:
1. 创建空对象 {}
2. 对象的 __proto__ 指向构造函数的 prototype
3. 构造函数以 this = 新对象执行
4. 返回该对象(构造函数没 return 对象时)
三、ES6 class 语法
class Person {
static create(name) { return new Person(name); } // 静态方法
#secret = '私有字段'; // 私有(ES2022)
constructor(name, age) {
this.name = name;
this.age = age;
}
hello() { return `hi ${this.name}`; } // 原型方法
get info() { return `${this.name} ${this.age}`; } // getter
}
const p = new Person('Tom', 20);
p.info; // "Tom 20"
typeof Person; // "function"(class 本质是构造函数)
四、继承 extends
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} 叫了一声`; }
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 必须先调 super(= 父构造函数)
this.breed = breed;
}
speak() { return `${this.name}(${this.breed})汪汪`; } // 重写
guard() { return `${this.name} 看门`; }
}
const d = new Dog('旺财', '柯基');
d.speak(); // "旺财(柯基)汪汪"
d instanceof Dog; // true
d instanceof Animal; // true(原型链)
五、原型链图谱
d.__proto__ === Dog.prototype
Dog.prototype.__proto__ === Animal.prototype
Animal.prototype.__proto__ === Object.prototype
Object.prototype.__proto__ === null
六、注意
- 原型方法放 prototype(共享)、实例属性放 constructor(独立);
- class 有提升但不建议先用后定义(暂时性死区);
- super 必须在 this 之前调用;
- hasOwnProperty 判断自有属性(in 运算符含原型)。
七、小案例:动物类继承体系
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} 发出声音`; }
static isAnimal(obj) { return obj instanceof Animal; }
}
class Cat extends Animal {
constructor(name, indoor = true) {
super(name);
this.indoor = indoor;
}
speak() { return `${this.name} 喵~`; }
get type() { return this.indoor ? '家猫' : '野猫'; }
}
class Dog extends Animal {
speak() { return `${this.name} 汪!`; }
fetch(ball) { return `${this.name} 捡回了 ${ball}`; }
}
// 多态:同一方法不同表现
const zoo = [new Cat('咪咪'), new Dog('旺财')];
zoo.forEach(a => console.log(a.speak()));
// 喵~ / 汪!
console.log(Animal.isAnimal(zoo[0])); // true
console.log(zoo[0].type); // 家猫
继承(extends + super)、重写(speak)、多态(zoo.forEach 统一调用)、getter、静态方法 —— 面向对象一次练全。
八、总结
prototype 共享方法、__proto__ 形成查找链;new 四步;class 是语法糖(constructor/静态/私有/继承);extends + super 实现继承,多态靠同名方法重写。