上面的方法怎么样用于原型继承和构造函数继承
时间: 2024-05-07 09:15:25 浏览: 14
对于原型继承,可以通过将子类的原型指向父类的实例来实现继承。例如:
```
function Parent() {
this.name = 'parent';
}
Parent.prototype.getName = function() {
return this.name;
}
function Child() {
Parent.call(this); // 调用父类构造函数,继承实例属性
this.type = 'child';
}
Child.prototype = Object.create(Parent.prototype); // 将子类原型指向父类实例,继承原型属性
Child.prototype.constructor = Child; // 修正子类构造函数指向
var child = new Child();
console.log(child.getName()); // 'parent'
```
对于构造函数继承,可以在子类构造函数中调用父类构造函数,并使用 call 或 apply 方法将父类实例属性绑定到子类实例上。例如:
```
function Parent() {
this.name = 'parent';
}
Parent.prototype.getName = function() {
return this.name;
}
function Child() {
Parent.call(this); // 调用父类构造函数,继承实例属性
this.type = 'child';
}
// 不需要继承原型属性
var child = new Child();
console.log(child.getName()); // TypeError: child.getName is not a function
```
可以看到,构造函数继承只继承了父类的实例属性,没有继承原型属性。因此,在使用时需要注意这一点。