call方法的使用bug--参数undefined

call/apply是函数原型定义的方法(Function.prorotype),在使用时要注意第一个形参(args[0]),一定是指向函数所要挂载的上下文对象--context,若对象非必须,则要将第一个参数置为null或undefined,不显示传入context,按照call/apply的实现过程,会将其他形参(args[1])作为调用上下文使用,很容易造成其他形参undefined错误,出错场景如下:

function myMatch(str){
        var rst = str.replace("{{","").replace("}}","");
        return rst;
    }

//给Array原型扩展自定义方法
    Array.prototype.myEach = function(f){
        var rst = [];
        for( var i=0;i<this.length;i++ ){
            var macther = f.call( this[i]);
            //var macther = f(this[i]);
            rst.push( macther );
        }
        return rst;
    }

   var arr = ["{{name}}","{{age}}"];

console.log( arr );

console.log( arr.myEach( myMatch ) );

出错原因在调用call的时候,this[i]被当做了挂在上下文context,真正有用的形参如str,则是undefined!

解决方案:

1.在无明显context需求下,可以不用call/apply形式,直接用f(this[i]);

2.无必要使用context,但使用call/apply,请将context置为null/undefined.

posted @ 2018-09-11 10:45  sophel  阅读(193)  评论(0编辑  收藏  举报