Mr.J--JS学习(继承模式发展史)

Javascript继承模式发展史

1.call/apply方法

Grand.prototype.LastName = "Y";
		
		function Grand(){
			
			
		}
		
		var grand = new Grand();
		
		Father.prototype = grand;
		function Father(){
			this.name = "hehe";
		}
		
		var father = new Father();
		
		Son.prototype = father;
		function Son(){
			
		}
		
		var son = new Son();
		
		
		
		function Person(name,age,sex){
			this.name = name;
			this.age = age;
			this.sex = sex;
		}
		
		function Student(name,age,sex,grade){
			Person.call(this,name,age,sex);
			this.grade = grade;
		}
		
		var student = new Student();

2.共有原型实现

		Father.prototype.LastName = "Young";
		
		function Father(){
			
		}
		
		function Son(){
			
		}
		//共有原型
		Son.prototype = Father.prototype;   
		
		var son = new Son();
		var father = new Father();

运行结果:

3.inherit 转换prototype

将第二种方法进行包装:

Father.prototype.LastName = "Young";
		
		function Father(){
			
		}
		
		function Son(){
			
		}
		
		function inherit(Target,Origin){
			Target.prototype = Origin.prototype;
		}
		
		//先继承后应用
		inherit(Son,Father);
		
		Son.prototype.sex =  "male";// 与Father.prototype指向同一空间 ,会改变father有sex属性
		
		var son = new Son();
		var father = new Father();

运行结果:

4.圣杯模式

Father.prototype.LastName = "Young";
		
		function Father(){
			
		}
		
		function Son(){
			
		}
		
		function inherit(Target,Origin){
			function F(){};
			F.prototype = Origin.prototype;
			Target.prototype = new F();			//与上面一行不能颠倒
			Target.prototype.constructor = Target;	//son的constructor归位
			Target.prototype.uber = Origin.prototype;   //储存继承信息
		}
		
		inherit(Son,Father);
		
		Son.prototype.sex =  "male";//此时father上面不会出现sex属性
		var son = new Son();
		var father = new Father();
		
		//son.__proto__ --> new F().__proto__ --> Father.prototype
		
		
		

修改第三种方法的bug。

运行结果:

Final  Yahoo inherit()方法

var inherit = (function(){
			//私有化变量   
			var F = function F(){};
			return function(Target,Origin){
			F.prototype = Origin.prototype;
			Target.prototype = new F();			//与上面一行不能颠倒
			Target.prototype.constructor = Target;	//son的constructor归位
			Target.prototype.uber = Origin.prototype;
			}	
		}());

闭包私有化,加大效率。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值