在JavaScript中,继承是通过原型链来实现的。每个JavaScript对象都有一个原型对象,当试图访问一个对象的属性时,如果该对象本身没有这个属性,就会去它的原型对象上查找,这个过程会一直持续到找到属性或者到达原型链的末端(即null
)。
以下是JavaScript中实现继承的几种方式:
通过将子类的原型设置为父类的实例来实现继承。
function Parent() {
this.name = 'parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
function Child() {
this.name = 'child';
}
// 继承Parent
Child.prototype = new Parent();
var child = new Child();
child.sayHello(); // 输出: Hello, child
在子类构造函数中调用父类构造函数,并使用call
或apply
方法来改变父类构造函数的上下文。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
function Child(name) {
Parent.call(this, name); // 继承Parent的属性
}
var child = new Child('child');
console.log(child.name); // 输出: child
child.sayHello(); // 报错: child.sayHello is not a function
注意:这种方式只能继承父类的属性,不能继承父类原型上的方法。
结合原型链继承和构造函数继承的优点,既可以继承父类的属性,也可以继承父类原型上的方法。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
function Child(name) {
Parent.call(this, name); // 继承Parent的属性
}
Child.prototype = new Parent(); // 继承Parent原型上的方法
Child.prototype.constructor = Child; // 修复constructor指向
var child = new Child('child');
child.sayHello(); // 输出: Hello, child
通过创建一个新对象,并将这个新对象的原型设置为另一个对象来实现继承。
function createObject(o) {
function F() {}
F.prototype = o;
return new F();
}
var parent = {
name: 'parent',
sayHello: function() {
console.log('Hello, ' + this.name);
}
};
var child = createObject(parent);
child.name = 'child';
child.sayHello(); // 输出: Hello, child
在原型式继承的基础上,对创建的对象进行扩展。
function createChild(parent) {
var child = createObject(parent);
child.name = 'child';
child.sayHello = function() {
console.log('Hello, ' + this.name);
};
return child;
}
var parent = {
name: 'parent',
sayHello: function() {
console.log('Hello, ' + this.name);
}
};
var child = createChild(parent);
child.sayHello(); // 输出: Hello, child
结合寄生式继承和组合继承的优点,是实现继承的一种更优方式。
function inheritPrototype(child, parent) {
var prototype = Object.create(parent.prototype); // 创建父类原型的副本
prototype.constructor = child; // 修复constructor指向
child.prototype = prototype; // 设置子类原型
}
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
function Child(name) {
Parent.call(this, name);
}
inheritPrototype(Child, Parent);
var child = new Child('child');
child.sayHello(); // 输出: Hello, child
constructor
指向。call
或apply
在子类构造函数中调用父类构造函数,或者在子类原型上使用Object.create
来继承父类原型。以上就是JavaScript中实现继承的几种方式及其相关概念、优势和常见问题解决方法。
领取专属 10元无门槛券
手把手带您无忧上云