js的apply函数"源码”

Function.prototype.apply=function(x){
    x = x || {};//防止this为null
    x['fn'] = this;
    var list = arguments[1] || [];
    var args = '';//参数列表
    var type;
    for (var i = 0; i<list.length;i++) {        
        if (typeof list[i] === 'string') {//参数是字符串,需要在两边加引号,因为在拼接参数的时候会被丢掉
            type = '"'+list[i] + '"';
        }
        else if (typeof list[i] === 'function') {//参数是函数的话,"反编译"出函数的代码
            type = list[i].toString();
        }
        else if (typeof list[i]  === 'object' ) {
            if (/function Array()/.test(list[i]['constructor'])) {//参数是数组则在数组两边加上[,]
                type = "[" + list[i] + "]";
            } else {
                type = JSON.stringify(list[i])//对象的话,json化,然后执行的时候反json化
            }    
        } else {
            type = list[i];//数字类型
        }
        args = args + type +',';
    }
    args = args.slice(0,args.length-1);//去掉最后的逗号
    var q = new Function('var x = arguments[0];x.fn('+args+')')//new Function的时候作用域是独立的,无法访问call里面的x,所以需要传进去
    q(x)
}
function parse_Array_Object(arg) {
    //可以npm install traverse-deep和结合js的map函数进行相应处理,主要是遍历arg的每一个元素,进行类型判断,然后返回相应的字符串
    //to do ..
}

function a(a){
    console.log(this,arguments)
}
a.apply(null,[1,2])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值