JavaScript学习笔记之Apply和Call

Apply和Call的作用就是继承,类似于PHP的extends。两者作用是一样的,但是用法上还是有点区别。talk is cheap show code~

Apply :

//apply
(function() {
    function person(name, age) {
        console.log(this) //三次调用person,上下文分别为:window, student, teacher
        if (!name) return;
        this.prototype.name = name;
        this.prototype.age  = age;
    }

    person();

    function student(name, age) {
        //person.apply(this, name, age); --second argument to Function.prototype.apply must be an array
        person.apply(student, [name, age]);
        console.log('My Name Is ' + this.name + ' ,Age Is ' + this.age);
    }

    function teacher(name, age, college) {
        person.apply(teacher, arguments);
        console.log('My Name Is ' + this.name + ' ,Age Is ' + this.age);
    }

    var student = new student('gaozhen', '22');
    var teacher = new teacher('qianwen', '23');
})()

Call :

//call
(function() {
    function person(name, age) {
        this.prototype.name = name;
        this.prototype.age  = age;
        console.log(this) //上下文分别为:student、teacher
    }

    function student(name, age) {
        person.call(student, name, age);
        console.log('This Student Name Is ' + this.name + ' ,Age Is ' + this.age);
    }

    function teacher() {
        person.call(teacher, arguments);
        console.log('This Teacher Name Is ' + this.name + ' ,Age Is ' + this.age);
    }

    var student = new student('gaozhen', '22');//This Student Name Is gaozhen ,Age Is 22
    var teacher = new teacher('qianwen', '23');//This Teacher Name Is [object Arguments] ,Age Is undefined
})()

Apply和Call从用法角度来讲,区别在于apply可以无需指定参数个数,通过auguements来弹性的进行传参,且传入参数必须为Array。而call则必须要指定传参,且传入的参数必须为Object。两者在传入的时候,都会改变继承函数的上下文(如果对象传入为空的话,则为全文)。如person直接执行的话,this输出为window,后续被继承时,分别为student和teacher

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值