实现extend js
在 JavaScript 中实现继承
JavaScript 中的继承可以通过多种方式实现,以下是常见的几种方法:
原型链继承
通过将子类的原型指向父类的实例来实现继承:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child() {}
Child.prototype = new Parent();
const child = new Child();
child.sayName(); // 输出 "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.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;
ES6 class 继承
使用 ES6 的 class 和 extends 关键字:

class Parent {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
Object.create() 实现继承
使用 Object.create() 创建原型对象:
const parent = {
sayHello() {
console.log('Hello');
}
};
const child = Object.create(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.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
inheritPrototype(Child, Parent);
选择哪种继承方式取决于具体需求,ES6 的 class 语法是最简洁现代的实现方式。






