无法从对象内部访问数组(未初始化)

时间:2015-09-04 16:00:05

标签: javascript node.js

example.js

var ApiActions = {
  pendingAjaxRequests: [],
  addRequest: function() {
      this.pendingAjaxRequests.push(1);
  }
}

ApiActions.addRequest();

console.log( ApiActions.pendingAjaxRequests );

module.exports = ApiActions;

在另一个档案中:

var ApiActions = require("./example");
ApiActions.addRequest();
console.log( ApiActions.pendingAjaxRequests );

出于某种原因,我得到了

Uncaught TypeError: Cannot read property 'push' of undefined

我似乎无法弄清楚为什么pendingAjaxRequests未初始化?我做错了什么?

1 个答案:

答案 0 :(得分:0)

//define class with name 'ApiActions'. then you can just use 'var a = new ApiActions();    
var ApiActions = function(){
     //define class member(not static)
     this.pendingAjaxRequests = [];
     //if you define variable like this, they will only exist in scope of this function and NOT in the class scope
     var array = [];
};

//use prototype to define the method(not static)
ApiActions.prototype.addRequest = function(){
     this.pendingAjaxRequests.push(1);
};

//this will define a static funciton (ApiActions.test() - to call it)
ApiActions.test = function(){
     this.pendingAjaxRequests.push(1);
};