JS继承三种方式

 

prototype继承


<script type = "text/javascript">
//继承1
   //父类
   function Person (name,age) {
	    this.name = name;
		this.age = age;
	 }
	 Person.prototype.country = "中国";
	 Person.prototype.study  = function(){
          alert(this.name+"-"+this.age+"岁,正在学习,勿扰!");
   }
   //子类
   function Teacher(school){
       this.school = school;
         
   }
   //核心继承
   Teacher.prototype = new Person("迟老师",26);
   var t = new Teacher("北爱小学");
   t.study(); 

</script>
 

构造函数继承

this.animal=Animal;给Person类的实例,扩展一个属性,该属性指向Animal类
this.animal();  调用Animal类(函数),此时Animal中的this就是Person类创建的实例


<script type = "text/javascript">
//继承2

   function Person () {
	    this.name = "robbin"
		this.age = 18;
		this.country = "中国";
        this.study  = function(){
          alert(this.name+"-"+this.age+"岁,正在学习,勿扰!");
	  }
   }

   function run(){
        alert(this.name);
      
   }
   
   //子类 通过构造函数传入
   function Teacher(school,fun){
       this.school = school;
	   this.run = fun;
	   this.person = Person;
	   this.person(); 
	   
	     
   }

   //核心继承
   var t = new Teacher("北爱小学",run); 
   console.debug(t);
   t.study(); 
  
</script>
 
 
 
 

通过apply或者call实现继承

<script type="text/javascript">
		function Person(name){
			this.name=name;
			
			/* //--★★★★★通过以下代码实现继承,核心语句就下面两句
			this.animal=Animal;//给Person类的实例,扩展一个属性,该属性指向Animal类
			this.animal();//  调用Animal类(函数),此时Animal中的this就是Person类创建的实例 */
			
			//--------下面两句话和上面的代码功能一致-------------
			//Animal.call(this);//这样做相当于this调用了Animal()
			Animal.apply(this);//这样做相当于this调用了Animal()
		}

		var p=new Person("张三");
		
		
		function Animal(){
			this.blood="red";
		}
		alert(p.blood);

	</script>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值