日期:2014-05-16 浏览次数:20537 次
?? ? ?关于javascript中call()和apply()方法的使用,网上有一博友已经写得非常清楚,链接地址如下:
关于JavaScript中apply与call的用法意义及区别
?
?在了解了javascript中call和apply方法的使用方法之后,下面具体讲一下继承的实现方式:
<html>
<head>
<title></title>
</head>
<body>
<script language="javascript" type="text/javascript">
function ClassParent(name){
this.name = name;
this.sayName = function(){
alert(this.name);
}
}
//一‘对象冒充
function ClassChild(name,sex){
this.newMethod = ClassParent;//函数名指针指向ClassParent;
this.newMethod(name);//调用该方法。
delete this.newMethod;//删除对ClassParent的引用,这样以后就不能再调用它了。
this.sex = sex;
this.saySex= function(){
alert(this.sex);
}
}
var obj = new ClassChild("jesen","nan");
obj.saySex();
obj.sayName();
//二、call()方法
function ClassChild2(name,sex){
ClassParent.call(this,name);
this.sex=sex;
this.saySex = function(){
alert(this.sex);
}
}
var obj2 = new ClassChild2("jesen2","nan2");
obj2.saySex();
obj2.sayName();
//三、apply()方法
function ClassChild3(name,sex){
ClassParent.apply(this,new Array(name));
//ClassParent.apply(this,arguments);此处可以使用参数对象arguments,当然只有是在超类中的参数顺序与子类中的参数顺序完全一致时才适用。
this.sex=sex;
this.saySex = function(){
alert(this.sex);
}
}
var obj3 = new ClassChild2("jesen3","nan3");
obj3.saySex();
obj3.sayName();
//四、原型链
function ClassPrototypeParent(){
}
ClassPrototypeParent.prototype.name="jesen4";
ClassPrototypeParent.prototype.sayName=function (){
alert(this.name);
}
function ClassPrototypeChild(){
}
ClassPrototypeChild.prototype = new ClassPrototypeParent();//原型链必须确保构造函数没有任何参数。
ClassPrototypeChild.prototype.name="jesen4child";
ClassPrototypeChild.prototype.sex="nan4child";
ClassPrototypeChild.prototype.saySex=function(){
alert(this.sex);
}
var objp = new ClassPrototypeParent();
var objc = new ClassPrototypeChild();
objp.sayName();
objc.sayName();
objc.saySex();
//五、混合方式
//javascript创建类得最好的方法是用构造函数定义属性,用原型方式定义方法。
</script>
</body>
</html>
???
JavaScript中有一个call和apply方法,其作用基本相同,但也有略微的区别。
先来看看JS手册中对call的解释:
说明白一点其实就是更改对象的内部指针,即改变对象的this指向的内容。这在面向对象的js编程过程中有时是很有用的。
引用网上一个代码段,运行后自然就明白其道理。