关于JS继承

关于JS的几种继承方式

圣杯模式

function inherit(son, father) {
	function T () {};
	son.prototype = new T();
	T.prototype = father.prototype;
	son.prototype.constructor = son;
	son.prototype.uber = father.prototype;
}

原型上的constructor默认指向他的构造函数,son的constructor应该指向son
我们希望构造出来的对象能够找到自己的超类——超级父类(究竟继承自谁)应该使用super,但super是保留字,所以使用uber
在这里插入图片描述
雅虎程序员写的圣杯模式继承,利用了立即执行函数,相对来说更高级

inherit = (function () {
	var T = function () {};
	return function (son, father) {
		T.prototype = father.prototype;
		son.prototype = new T();
		son.prototype.constructor = son;
		son.prototype.uber = father.prototype;
	}
}());

构造函数继承

类的继承

  • extends 继承,用于类的定义
  • super
    1. 当做函数调用,表示父类构造函数
    2. 当做对象使用,表示父类的原型
class Father {
	constructor (type, name, age, sex) {}
	methods() {}
}
class Son extends Father{
	constructor (name, age, sex) {
		super(type, name, age, sex)
	}
}

注意:ES6要求,如果定义了constructor,并且该类是子类,则必须在constructor的第一行手动调用父类的构造函数,如果子类不写constructor,则会自动调用父类构造器,该构造器需要的参数和父类一致

小知识:JS实现抽象类
抽象类:一般是父类,不能通过该类创建对象

class Father {
	constructor (type, name, age, sex) {
		if (new target === Feater) {
			throw new TypeError("不能直接创建Father的对象,应该通过子类创建")
		}
	}
	methods() {}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值