js继承如何实现的
继承的实现方式
JavaScript 中的继承主要通过原型链实现,以下是几种常见的继承方式:
原型链继承
通过将子类的原型指向父类的实例实现继承:
function Parent() {
this.name = 'parent';
}
Parent.prototype.getName = function() {
return this.name;
};
function Child() {}
Child.prototype = new Parent();
const child = new Child();
console.log(child.getName()); // 'parent'
构造函数继承
在子类构造函数中调用父类构造函数:
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.getName = function() {
return 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', 10);
console.log(child.getName()); // 'child'
原型式继承
基于已有对象创建新对象:
const parent = {
name: 'parent',
getName: function() {
return this.name;
}
};
const child = Object.create(parent);
child.name = 'child';
console.log(child.getName()); // 'child'
寄生式继承
在原型式继承基础上增强对象:
function createChild(parent) {
const child = Object.create(parent);
child.sayHello = function() {
console.log('Hello');
};
return child;
}
const parent = { name: 'parent' };
const child = createChild(parent);
child.sayHello(); // 'Hello'
寄生组合式继承
最理想的继承方式:
function inheritPrototype(child, parent) {
const prototype = Object.create(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function() {
return this.name;
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
const child = new Child('child', 10);
console.log(child.getName()); // 'child'
ES6类继承
使用class和extends语法:
class Parent {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
const child = new Child('child', 10);
console.log(child.getName()); // 'child'
每种继承方式都有其适用场景和优缺点,实际开发中应根据需求选择合适的继承方式。ES6类继承是目前最简洁和推荐的方式。







