js—深入原型之三继承

1、通过改变原型指向来实现继承:

缺陷:实现继承的同时直接初始化了属性,继承过来的属性的都是一样的

解决:继承的时候不用改变原型的指向,直接使用借用构造函数(call方法)

              function Person(name,age,sex,weight){
			this.name=name;
			this.age=age;
			this.sex=sex;
			this.weight=weight;
		}
		Person.prototype.sayHi=function(){
			console.log('你好啊啊啊');
		}
		//借用构造函数:call(实例对象,属性,属性.....)
		function Student(name,age,sex,weight,score){
			Person.call(this,name,age,sex,weight);
			this.score=score;
		}
		
		var stu1=new Student('小明',20,'女',87);
		console.log(stu1.name+'  ||  '+stu1.age+'  ||  '+stu1.sex+'  ||  '+stu1.weight);
		var stu2=new Student('小成',21,'男',90);
		console.log(stu2.name+'  ||  '+stu2.age+'  ||  '+stu2.sex+'  ||  '+stu2.weight);
		var stu3=new Student('小张',19,'男',98);
		console.log(stu3.name+'  ||  '+stu3.age+'  ||  '+stu3.sex+'  ||  '+stu3.weight);
		stu3.sayHi();

结果:

(方法无法继承)

2、组合继承:改变原型的指向(解决方法的继承,实例化不用传参)+借用构造函数(解决属性的复用继承)

               function Person(name,age,sex,weight){
			this.name=name;
			this.age=age;
			this.sex=sex;
			this.weight=weight;
		}
		Person.prototype.sayHi=function(){
			console.log('你好啊啊啊');
		}
		//借用构造函数:call(实例对象,属性,属性.....)
		function Student(name,age,sex,weight,score){
			Person.call(this,name,age,sex,weight);
			this.score=score;
		}
		//不用传参
		Student.prototype=new Person();
		//自定义的方法
		Student.prototype.school=function(){
			console.log('我是大学生');
		}
		var stu1=new Student('小明',20,'女',87);
		console.log(stu1.name+'  ||  '+stu1.age+'  ||  '+stu1.sex+'  ||  '+stu1.weight);
		var stu2=new Student('小成',21,'男',90);
		console.log(stu2.name+'  ||  '+stu2.age+'  ||  '+stu2.sex+'  ||  '+stu2.weight);
		var stu3=new Student('小张',19,'男',98);
		console.log(stu3.name+'  ||  '+stu3.age+'  ||  '+stu3.sex+'  ||  '+stu3.weight);
		//继承的方法
		stu3.sayHi();
		//自己的方法
		stu3.school();

结果:

小明  ||  20  ||  女  ||  87
小成  ||  21  ||  男  ||  90
小张  ||  19  ||  男  ||  98
你好啊啊啊
我是大学生

3、拷贝继承:把一个对象中的属性或者方法直接复制到另一个对象中

    另建立一个空间

4、数组中函数调用

                 var  arr=[
		    function (){
		    	console.log('first blood');
		    },
		    function (){
		    	console.log('double kill');
		    },
		    function (){
		    	console.log('trible kill');
		    },
		    function (){
		    	console.log('quatary kill');
		    },
		    function (){
		    	console.log('penta  kill');
		    },
		    function (){
		    	console.log('legendary');
		    }
		];
		arr.forEach(function(ele){
			ele();
		});


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值