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

版权声明:转载请标明出处 https://blog.csdn.net/Ms_yjk/article/details/86605601

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;
			}	
		}());

闭包私有化,加大效率。

猜你喜欢

转载自blog.csdn.net/Ms_yjk/article/details/86605601
今日推荐