Uncaught TypeErroe: Uncaught TypeError: Cannot call method 'push' of undefined 和 Uncaught TypeError: undefined is not a function

1.Uncaught TypeError: undefined is not a function

情景描述:

function test(){

this.num=1;

};

$(function(){

  var test=new test();    // 当这条语句执行时,一开始var test定义为undefined类型,当执行到new test()报错检查到test为一个function,语句报错,此次变量不能使用和function test同名的test名变量,将变量改名为_test或其他

});

2.Uncaught TypeError: Cannot call method 'push' of undefined

情景描述:

test1.js(非实际脚本)

function item(ID,Name)

{

self=this;

self.ID=ID;

self.Name=Name;

}

function s1(){

self=this;

self.testarray1=ko.observableArray();

self.loadtestarray1=function(){

 

     $.getJSON("/api/Stylist", function (data) {
          $.each(data, function (index, item) {
                self.testarray1.push(new item(item.ID,item.Name);
           });
     });

  }

}

$(function(){

   var s1=new s1();

   s1.loadtestarray1();

});

test2.js 示例(非实际脚本)

function s2(){

self=this;

self.testarray2=ko.observableArray();

self.loadtestarray2=function(){

        $.getJSON("/api/Stylist", function (data) {
               $.each(data, function (index, item) {
                 self.testarray2.push({ ID:item.ID,Name:item.Name});
                });
         });

      }

}

$(function(){

   var s2=new s2();

   s2.loadtestarray2();

});

在一个页面中同时饮用了test1.js和test2.js,运行后报错Uncaught TypeError: Cannot call method 'push' of undefined。

原因分析:单步调试跟踪self变量值的变化情况,首先s1()函数先运行self赋值给了一个包含testarray1数组的object, 然后s2()

函数运行self赋值给了testarray2数组的object,接着s1.loadtestarray1()函数先执行获取一组数据,并跳入了Item函数,self此

时变成了Item对象,之后执行完后跳入执行s2.loadtestarray2()函数,此时发现self应该变成了Item对象。self.testarray2已是

undefined类型了,因为Item对象自然不包含testarray2数组,故此时调用self.testarray2.push方法,self.testarray这个undefined

类型为定义push方法,调试器报错 Uncaught TypeError: Cannot call method 'push' of undefined。

当多个js中假若要以其他变量替换this,应该命名不一样。,如self1,self2,当然要取个有意义的命名。

原文地址:https://www.cnblogs.com/lushuicongsheng/p/2646906.html