js的call函数"源码"

来源:互联网 发布:php固定资产管理系统 编辑:程序博客网 时间:2024/05/16 14:31

暂时不支持复杂的变量类型。。。

Function.prototype.call=function(x){    x = x || {};    x['fn'] = this;    var args = '';//参数列表    var type;    for (var i = 1; i<arguments.length;i++) {               if (typeof arguments[i] === 'string') {//参数是字符串,需要在两边加引号,因为在拼接参数的时候会被丢掉            type = '"'+arguments[i] + '"';        }        else if (typeof arguments[i] === 'function') {//参数是函数的话,"反编译"出函数的代码            type = arguments[i].toString();        }        else if (typeof arguments[i]  === 'object' ) {//数组和对象可能含有复杂的组合类型数据,可以通过遍历变量转成字符串            if (/function Array()/.test(arguments[i]['constructor'])) {//参数是数组则在数组两边加上[,]                type = "[" + arguments[i] + "]";            } else {                type = JSON.stringify(arguments[i])//对象的话,json化,然后执行的时候反json化            }           } else {            type = arguments[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.call({d:1},2,'s',[1,2,3],{s:1},function() {})
0 0
原创粉丝点击