• 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.

    路漫漫其修远兮,吾将上下而求索。 May stars guide your way⭐⭐⭐
  • 相关阅读:
    Windows 系统变量大全
    linux编程
    CSS 对齐操作
    php 和 表单 简单交互
    HTML <input> placeholder 属性
    HTML <label> 标签
    Chap-4 Section 4.4 C++相关问题
    Chap-4 Section 4.3 COMMON块
    Chap-4 Section 4.2.4 指令修正方式
    Chap-4 Section 4.2.3 符号解析
  • 原文地址:https://www.cnblogs.com/surfer/p/9626227.html
Copyright © 2020-2023  润新知