首先我们创建一个父类:

// 创建一个父类构造函数
function Parent () {
	this.parentProperty = '父类属性';
}
// 为父类添加一个原型方法
Parent.prototype.getParentProperty = function () {
	return this.parentProperty;
}

此时的原型链是这样的:
JS基础--子类型重写超类型方法原型链图解

接下来创建一个子类,使子类继承父类(即子类的原型为父类的实例):

// 创建一个子类构造函数
function Children () {
	this.childrenProperty = '子类属性';
}
// 继承Parent
Children.prototype = new Parent();

此时的原型链是这样的:
JS基础--子类型重写超类型方法原型链图解

重写超类型中的方法:

// 重写超类中的方法
Children.prototype.getParentProperty = function () {
	return '这是重写的父类方法';
}
// 创建自己的方法
Children.prototype.getChildrenProperty = function () {
	return '这是自己的方法';
}

原型链:
JS基础--子类型重写超类型方法原型链图解

创建实例

var instance = new Children();
instance.getParentProperty(); // 返回:"这是重写的父类方法"

原型链:
JS基础--子类型重写超类型方法原型链图解

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-06
  • 2021-09-11
  • 2022-01-06
  • 2021-12-12
猜你喜欢
  • 2022-03-05
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2022-01-28
  • 2022-01-26
  • 2022-12-23
相关资源
相似解决方案