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?我究竟做错了什么?
最佳答案
//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);
};
关于javascript - 无法从内部对象访问数组(未初始化),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32402182/