javascript【继承实现方式 】

一.call() 和 apply()用法

这两个方法,之前确实没有使用过,看起来貌似以后会为我省点代码,直接做个demo 吧。

1. 

 function Animail(){
      this.name="动物";
	  this.showName = function(){
		  alert(this.name);
	  };
    }
    function Cat(){
	   this.name = "猫咪";
	}
	var animail = new Animail();
	var cat = new Cat();
    animail.showName.call(cat);
打印效果:



2.  具体applay 和 call 作用一样,只是语法不一样

      function myFunction(a,b,c){
		this.a = a;
		this.b = b;
		this.c = c;

	}
    var obj = new Object();
    alert(obj.a); // undefined
    myFunction.apply(obj,[2,5,8]);
   //myFunction.call(obj,2,5,8);
    alert(obj.a);//2

二. prototype 

function Animail(){}

    Animail.prototype.name = "动物";
	Animail.prototype.age = 2;
	Animail.prototype.type = "001";
	function Cat(){
		this.name = "猫咪";
		this.age = 3;
	}

    Cat.prototype = Animail.prototype;

	var animail = new Animail();
	var cat = new Cat();
     
	 
	 alert(cat.name); // cat 自己的name:猫咪
	 alert(cat.age); //cat 自己的age:3
	 alert(cat.type); //Animail的type:2


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值