Home  >  Q&A  >  body text

JavaScript函数同名会被覆盖,怎么解决?

JavaScript函数同名会被覆盖,怎么解决?

末日的春天末日的春天2765 days ago1191

reply all(2)I'll reply

  • 数据分析师

    数据分析师2017-10-01 01:10:37

    JavaScript functions with the same name will be overwritten. How to solve this problem? -PHP Chinese website Q&A-JavaScript functions with the same name will be overwritten, how to solve it? -PHP Chinese website Q&A

    Let’s take a look and learn.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-03-27 09:49:52

    在JavaScript脚本中,局部函数与外围函数同名,则会覆盖掉外网函数,即变量可以重复定义。

    A =  function(){
        var me = this;
        me.method1 = function(){
            var items = [1,2,3,4,5];
            for(var i=0;i<items.length;i++){
                if(1){
                    var items = [6,7,8];
                     
                    if(items.length == 0){
                        alert('test is ok!');
                    }
                    alert(items[i]);
                }
            }
        }
    }

    局部变量items的定义如下:

    var items = [5,6,7];

    将覆盖外网变量的定义:

    var items=[1,2,3,4,5];

    循环只能执行3次。

    解决的办法是使用不同的函数名,避免函数同名。


    reply
    0
  • Cancelreply