JS basis - subtype prototype chain override method illustrated supertype

First we create a parent class:

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

At this time, this prototype chain:
1 prototype chain

Next, create a subclass, the subclass inherits the parent class (that is, instances of the parent class prototype subclass):

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

At this time, this prototype chain:
2 prototype chain

Overriding methods super-types:

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

Prototype chain:
Prototype chain 3

Create an instance of

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

Prototype chain:
4 prototype chain

Published 18 original articles · won praise 0 · Views 2522

Guess you like

Origin blog.csdn.net/weixin_36465540/article/details/89885292