在 JavaScript 中,实现继承和类构造函数的方式有多种,其中比较常用的方式是使用原型链和构造函数相结合的方式。
原型链继承是通过将子类的原型指向父类的实例来实现继承的。具体实现步骤如下:
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function () {
console.log('My name is ' + this.name);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.sayAge = function () {
console.log('I am ' + this.age + ' years old.');
}
类构造函数继承是通过在子类构造函数中调用父类构造函数来实现继承的。具体实现步骤如下:
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function () {
console.log('My name is ' + this.name);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.sayAge = function () {
console.log('I am ' + this.age + ' years old.');
}
以上就是实现继承和类构造函数的常见方式。需要注意的是,在使用原型链继承时,子类的实例共享父类实例的属性和方法,可能会导致不可预期的问题;在使用类构造函数继承时,父类的属性和方法不会被共享,但是父类的实例方法也不能被子类直接访问。