在 JavaScript 中,可以使用原型链实现继承。
首先,创建一个父类(也称为超类):
function Parent() {
this.name = '父类';
}
然后,通过创建一个新的对象并将其设置为子类(也称为派生类)的原型来实现继承:
function Child() {
this.name = '子类';
}
Child.prototype = new Parent();
现在,子类可以继承父类的属性和方法:
var child = new Child();
console.log(child.name); // 输出:“子类”
需要注意的是,使用原型链继承可能会导致一些副作用,例如父类中的属性可能会被所有子类实例共享。因此,可以使用借用构造函数的方式来避免这些问题:
function Parent() {
this.names = ['John', 'David'];
}
function Child() {
Parent.call(this);
}
var child1 = new Child();
child1.names.push('Sarah');
console.log(child1.names); // 输出:['John', 'David', 'Sarah']
var child2 = new Child();
console.log(child2.names); // 输出:['John', 'David']
在这个例子中,父类的属性 names
不会被所有子类实例共享,因为它们是通过借用构造函数的方式继承的。