我有一个对象:
myObj.js
MyObj={
myArray: new Array(),//An ARRAY DEFINED HERE, BUT seems should be somewhere else
test_1: function(){
//HERE!!! Modify "myArray"
},
others: function(){
}
}
myfunc.js
var myFunc= function(){
};
myFunc.prototype={
start: function(){
for(var i=0; i<DynamicNumber; i++){
MyObj.test_1
}
}
}
我通过以下方式运行代码:
var my = new MyFunc();
my.start();
如您所见,my.start()
运行时,它会调用test_1()
函数在MyObj中多次修改myArray
,我想在某个位置定义myArray
,以便每次运行test_1()
时,它知道myArray
的当前内容。那就是我希望MyObj.test_1()
函数在每次修改后都知道'myArray
'的当前内容。继续跟踪“ myArray
”。
我在哪里以及如何定义此'myArray'?
也许使用构造函数:
MyObj = function() {
var myArray = new Array();
var test_1 = function() {
// In this scope, you will have access to myArray
};
var others = function(){
};
//Public variables
this.test_1 = test_1;
this.others = others;
}
并使用它:
myFunc.prototype={
start: function(){
var myObj = new MyObj();
for(var i=0; i<DynamicNumber; i++){
myObj.test_1();
}
}
}