JS继承之巧用call()方法

<!DOCTYPE html>
<html>
<head>
	<title>JS继承之巧用call()方法</title>
	<script type="text/javascript">
		
	   function ClassA(sColor) {
			
			this.color = sColor;
			
			this.sayHello = function AsayHello(){
				alert("Hello from ClassA ! --" + this.color);
			};
			
       };
	   
	   function ClassB(sColor,sName){
			
			ClassA.call(this,"blue");
			
			this.name =  sName;
			alert("now,we can get the color = " + this.color);
	   };
	   
	   alert(new ClassB().color); //AsayHello 是不可见的,不能在此使用!
	   
	</script>
</head>
<body>
	<H1>call()方法</H1>
	<P> call()方法是与经典的对象冒充方法最相似的方法。它的第一个参数用作this的对象,其他参数都直接传递给函数自身。例如:</br></br>

        function sayColor(sPrefix, sSuffix) {</br>

              alert(sPrefix + this.color + sSuffix);</br>

        }</br></br>

 

        var obj = new Object();</br>

        obj.color = "red";</br>

        sayColor.call(obj, "Color is", ", a nice color"); </br>
		// output: Color is red, a nice color</br></br>

        在这个例子中,函数sayColor()在对象外定义,即使它不属于任何对象,也可以应用关键字this。对象obj的color属性等于"red"。调用call()方法时,第一个参数是obj,说明应该赋予sayColor()函数中的this关键字值是obj。第二个和第三个参数是字符串。它们与sayColor()函数中的参数sPrefix和sSuffix匹配。</br>

        要与继承机制的对象冒充方法一起使用该方法,只需将前三行的赋值、调用和删除代码替换即可:</br></br>

        function ClassB(sColor, sName) { </br>

              //this.newMethod = ClassA; </br>

              //this.newMethod();</br>

              //delete this.newMethod;</br>

              ClassA.call(this, sColor);</br>

 

              this.name = sName;</br>

              this.sayName = function() {</br>

                   alert(this.name);</br>

              };</br>

        }</br></br>

        这里,想让ClassA中的关键字this等于新创建的ClassB对象,因此this是第一个参数。第二个参数sColor对两个类来说都是唯一的参数。
	</P>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值