您的位置:首页 > 移动开发

javascript继承--call()和apply实现继承

2012-04-08 18:35 375 查看
  call方法是Function对象中的方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用call方法,call方法的第一个参数会被传递给函数中的this,从第2个参数开始,挨个赋值给函数中的参数

function person(name){
alert(name+"  :  "+this.hobby);
}
var obj=new Object();
obj.hobby="打酱油";
person.call(obj,"小张");


(2)

<script language="javascript" type="text/javascript">
function Parent(name){
this.name=name;
this.sayHello=function(){
alert(this.name);
}
}
function Child(name,hobby){
this.hobby=hobby;
Parent.call(this,name);
this.say=function(){
alert(this.name+"  :  " +this.hobby);
}
}
var ch=new Child("小明","打酱油");
ch.sayHello();
ch.say();
</script>


apply方法实现继承

function Parent(name){
this.name=name;
this.sayHello=function(){
alert(this.name);
}
}
function Child(name,hobby){
this.hobby=hobby;

Parent.apply(this,[name]/* 或者new Array(name) */);
this.say=function(){
alert(this.name+"  :  "+this.hobby);
}
}
var ch=new Child("小明","打酱油");
ch.sayHello();
ch.say();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: