javascript类方法加载json文件问题

时间:2016-08-11 07:16:20

标签: javascript json

我在下面有一个类设置,但事情大部分都有效,但是当调用json.onjload时,我在控制台声明中一直出现错误" Uncaught TypeError: Cannot read property of 'push' of undefined"

如何解决此错误?

var Clazz = new function(){
  this.library = [];

  this.add_library = function(file){
    var json = new XMLHttpRequest();
    json.overrideMimeType("application/json");
    json.open("GET", file, false); //needs to be synchronise
    json.onload = function(){
      this.library.push(JSON.parse(json.responseText));
      do something...
    };
    json.send(null);
  };
}

Clazz.add_library("path/file.json");

解决方案

this.library.push(...);更改为Clazz.library.push(...);

3 个答案:

答案 0 :(得分:0)

因为范围在this.add_library

内发生了变化
var Clazz = new function(){
  this.library = [];
    var that = this;

  this.add_library = function(file){
    var json = new XMLHttpRequest();
    json.overrideMimeType("application/json");
    json.open("GET", file, false); //needs to be synchronise

    json.onload = function(){
        console.log(that)
      that.library.push(JSON.parse(json.responseText));
      //do something...
    };
    json.send(null);
  };
}

new Clazz.add_library("path/file.json");

答案 1 :(得分:0)

尝试:

var Clazz = new function(){
  this.library = [];

  this.add_library = (file) => {
    var json = new XMLHttpRequest();
    json.overrideMimeType("application/json");
    json.open("GET", file, false); //needs to be synchronise
    json.onload = () => {
      this.library.push(JSON.parse(json.responseText));
      do something...
    };
    json.send(null);
  };
}

或者您必须使用函数.bind(this),因为您在函数范围内对this的可见性有疑问。

答案 2 :(得分:0)

你遇到的问题是上下文。基本上,JavaScript有this的几种不同情况,您的示例使用其中两种:

  1. 方法调用 - this是指使用方法的对象。
  2. 函数调用 - this引用全局对象或undefined中的strict mode
  3. 让我们看看您的代码(我会稍微调整您的代码以获得更多说明):

    var Clazz = { // this code does the very same thing as `new function()`
        library: [], 
    
        add_library: function(file){ 
            // here if you use `this.library`, you would refer to the `library` field
            // and the code works perfectly fine, because `this` refers to the object Clazz
            json.onload = function(){
                this.library.push(JSON.parse(json.responseText));
                // ...on the other hand here `this` refers to the global object,
                // because `json.onload` is a function, even though it is inside a method `add_library`
            };
        };
    }
    

    如何解决这个问题?有几种方法:

    1. 使用.bind()

      json.onload = function(){
          this.library.push(JSON.parse(json.responseText));
      }.bind(Clazz);
      
    2. 将上下文分配给变量:

      const self = this;
      json.onload = function(){
          self.library.push(JSON.parse(json.responseText));
      }
      
    3. 使用箭头功能:

      json.onload = () => {
          this.library.push(JSON.parse(json.responseText));
      }