2015-09-04 76 views
1

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 

我可以” t似乎找出为什么pendingAjaxRequests未初始化?我究竟做错了什么?

回答

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); 
}; 
+0

你可以添加一个解释这个代码是干什么的吗? –

+0

@NateBarbettini,创建类ApiAction并定义'pendingAjaxRequests'属性,该属性对于此类的每个实体(非静态)都是唯一的。 然后定义一个函数'addRequest'也不是静态的 –

+1

谢谢。如果你用上面的详细解释更新了你的答案,那么它可能不会得到降低成绩:) –