js 实现面向对象
原型链继承
利用原型链实现继承是 JavaScript 中最基本的方式。每个构造函数都有一个原型对象,原型对象包含一个指向构造函数的指针,实例包含一个指向原型对象的内部指针。
function Parent() {
this.name = 'parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {
this.name = 'child';
}
Child.prototype = new Parent();
const child = new Child();
child.sayName(); // 输出 'child'
构造函数继承
在子类型构造函数的内部调用超类型构造函数,通过使用 apply() 或 call() 方法在新创建的对象上执行构造函数。
function Parent(name) {
this.name = name;
}
function Child(name) {
Parent.call(this, name);
}
const child = new Child('child');
console.log(child.name); // 输出 'child'
组合继承
将原型链继承和构造函数继承组合到一起,既通过在原型上定义方法实现函数复用,又能保证每个实例都有独立的属性。

function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child('child', 18);
child.sayName(); // 输出 'child'
console.log(child.age); // 输出 18
原型式继承
借助原型基于已有对象创建新对象,同时不必创建自定义类型。
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
const parent = {
name: 'parent',
sayName: function() {
console.log(this.name);
}
};
const child = object(parent);
child.name = 'child';
child.sayName(); // 输出 'child'
寄生式继承
创建一个仅用于封装继承过程的函数,该函数在内部以某种方式来增强对象,最后返回对象。

function createAnother(original) {
const clone = Object.create(original);
clone.sayHi = function() {
console.log('hi');
};
return clone;
}
const parent = {
name: 'parent',
sayName: function() {
console.log(this.name);
}
};
const child = createAnother(parent);
child.sayName(); // 输出 'parent'
child.sayHi(); // 输出 'hi'
寄生组合式继承
通过借用构造函数来继承属性,通过原型链的混成形式来继承方法,不必为了指定子类型的原型而调用超类型的构造函数。
function inheritPrototype(child, parent) {
const prototype = Object.create(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
const child = new Child('child', 18);
child.sayName(); // 输出 'child'
console.log(child.age); // 输出 18
ES6 Class 继承
ES6 引入了 class 语法糖,使得面向对象编程更加直观和易于理解。
class Parent {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
const child = new Child('child', 18);
child.sayName(); // 输出 'child'
console.log(child.age); // 输出 18






