day13---继承inherit

本文探讨了JavaScript中实现继承的常见方式及其存在的问题。通过分析原型链的特性,介绍了圣杯模式这一改进方案,该模式能有效避免子类原型修改影响父类对象的情况,确保了继承的健壮性和独立性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们常用下列方式来完成继承

	Father.prototype.lastName="Liu";
	function Father(){}
	function Son(){}
	Son.prototype = Father.prototype;
	var son = new Son;
	var father = new Father;
	console.log(son.lastName);//Liu
	console.log(father.lastName);//liu

或者将继承用函数表示

	Father.prototype.lastName = "Liu";
	function Father(){}
	function Son(){}
	function inherit(Target Origin){
		Target.prototype = Origin.prototype;
	}
	inherit(Son,Father);
	var son = new Son();
	console.log(Son.lastName)//Liu

但以上方式存在缺点。
我们给son的原型添加属性son.prototype.money:100;
同时构建一个新的对象var father=new Father();
此时如果我们访问father.money,不难发现father对象里并没有money属性,但结果却是father.money=100。此时son.prototype.money与father.prototype.money指向同一个。
为避免此种情况,将代码进行完善,从而推出一种完美的模式-----圣杯模式。

	function inherit(Target,Origin){
		function F(){};
		F.prototype = Origin.prototype;
		Target.prototype = new F();
		Target.prototype.constructor =Target;
		Target.prototype.uber=Origin.prototype;//查看继承自谁
	}
	Father.prototype.lastName="Liu";
	function Father(){}
	function Son(){}
	inherit(Son,Father);
	var son = new Son();
	var father = new Father();

在继承中间添加一个新的对象,来形成原型链。这样一来,解决了上面的问题----更改son的原型但不改变father的属性。

——-在努力,再努力

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值