手写实现apply函数

 Function.prototype.myapply=function(content) {
        var res;
        //console.log(this);
        if(typeof this != "function"){
            console.log("not a function");
        }else{
            content = content || window;   //es6默认参数 有参数取content,无参数取window
            content.fn = this;   //apply第一个参数为this要重新指向的对象
            if(arguments[1]) {   //如果有后续参数
               res = content.fn(arguments[1]);
            } else{
                res = content.fn();
            }
        }
        delete content.fn;   //不删除会导致实例化的对象多了一个fn的函数,在该例子中,fn为Parent()
        return res;
    }


        function Parent(work){
            this.work = work;
        }
        function Child(name,work){
            this.name = name;
            Parent.myapply(this,work);
        }
        var child = new Child("张三","工人");
        console.log(child,child.work,child.name);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值