前端JavaScript中的继承模式

传统形式(原型链继承)

Grand.prototype.lastName = 'hkp';
		function Grand(){

		}

		var grand = new Grand();

		Father.prototype = grand;
		function Father(){
			this.name = 'baba'
		}
		
		var father = new Father();

		Son.prototype = father;
		function Son(){

		}
		var son = new Son(); 
		//既有lastName,也有name,过多的继承了没有的属性

借用构造函数

	function Animal(name,age){
			this.name = name;
			this.age = age;
		}
		function Dog(name,age,grade){
			Animal.call(this,name,age);
			this.grade = grade;
		}
		var dog = new Dog('狗蛋',18,1);
		//不能继承构造函数的原型
		//每次构造函数都要多走一个函数

共享原型

	Father.prototype.lastName = 'hkp';
		function Father(){

		}

		function Son(){

		}
		Son.prototype = Father.prototype;

		Son.prototype.name = 'ji';

		var son = new Son();
		var father = new Father();
		//father对象也具有了name属性
		//不能随便改动自己的原型

圣杯模式

相传如果能找到圣杯而喝下其盛过的水就将返老还童、死而复生并且获得永生

		var inherit = (function(){
			function F(){};
			return function(Target,Origin){
				F.prototype = Origin.prototype; 
				Target.prototype = new F();//通过函数F实现原型链继承
				Target.prototype.constructor = Target;//指向构造该对象的构造函数
				Target.prototype.order = Origin.prototype;//指向真正继承的父级
			}
		})()

		Father.prototype.lastName = 'hkp';
		function Father(){

		}
		function Son(){

		}
		inherit(Son,Father);
		var son = new Son();
		var father = new Father();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值