js中apply和call方法的应用

本文介绍JavaScript中通过Function.apply实现对象继承的方法,展示了如何使一个对象继承另一个对象的属性和方法,并提供了一个具体的学生类继承人类的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对象的继承,就是:Function.apply(当然使用Function.call也是可以的)

apply方法能劫持另外一个对象的方法继承另外一个对象的属性

Function.apply(obj,args)方法能接收两个参数

obj:这个对象将代替Function类里this对象

args:这个是数组,它将作为参数传给Function(args-->arguments)

apply示范代码如下:

 <script>
function Person(name,age){   //定义一个类,人类
    this.name=name;     //名字
    this.age=age;       //年龄
    this.sayhello=function(){alert("hello")};
}
function Print(){            //显示类的属性
    this.funcName="Print";
    this.show=function(){
        var msg=[];
        for(var key in this){
            if(typeof(this[key])!="function"){
                msg.push([key,":",this[key]].join(""));
            }
        }
        alert(msg.join(" "));
    };
}
function Student(name,age,grade,school){    //学生类
     console.log(typeof arguments);
    Person.apply(this,arguments);
    Print.apply(this,arguments);
    this.grade=grade;                //年级
    this.school=school;                 //学校
}
var p1=new Person("jake",10);
p1.sayhello();                                  //  hello
var s1=new Student("tom",13,6,"清华小学");
s1.show();                                   //   name:tom age:13 funcName:Print grade:6 school:清华小学
s1.sayhello();                               // helo  
alert(s1.funcName);                          // Print 
</script>

总结: a.apply(b,["zhou","23"]) // b继承a
       a.call(b,arg1,arg2);  // b继承a 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

和你一起去月球

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值