子类中重写 this.method=method
时间: 2023-09-24 17:11:48 浏览: 40
可以通过在子类中重写 `this.method` 属性来实现对父类方法的重写。具体实现方法如下:
```
// 父类
function Parent() {}
Parent.prototype.method = function() {
console.log('Parent method');
}
// 子类
function Child() {}
// 继承父类
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// 重写方法
Child.prototype.method = function() {
console.log('Child method');
}
// 创建子类实例
var child = new Child();
// 调用重写后的方法
child.method(); // 输出 "Child method"
```
在子类中重写 `this.method` 属性,可以覆盖父类中同名的方法实现,实现对父类方法的重写。同时,在子类中可以通过 `super` 关键字来调用父类中被覆盖的方法。例如:
```
// 子类
function Child() {}
// 继承父类
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// 重写方法
Child.prototype.method = function() {
// 调用父类方法
Parent.prototype.method.call(this);
console.log('Child method');
}
// 创建子类实例
var child = new Child();
// 调用重写后的方法
child.method(); // 输出 "Parent method" 和 "Child method"
```
在子类的重写方法中使用 `Parent.prototype.method.call(this)` 调用父类方法,可以实现在子类中调用被覆盖的父类方法的效果。