<!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>
JS继承之巧用call()方法
最新推荐文章于 2021-12-17 16:49:20 发布