我希望能够增加/更改对象内部参数的值。我希望通过访问在另一个函数中递增的变量的值来更改值。
下面的示例代码显示了我要执行的操作。我希望options.number
内部的i
随着masterLoop
的增加而增加。
我知道i
不在function calc()
的范围内定义,但是我想不出一种在保持这种通用代码结构的情况下检索i
值的方法。 。
(function masterLoop(i) {
setTimeout(function() {
++i;
masterLoopStage = i;
console.log('Stage is: ' + i);
masterLoop(i);
}, 5000)
})(1);
function calc() {
number = i; // I know i isn't defined in this scope, but I can't figure out how access the incrementing value of i inside this function
return number;
}
var options = {
number: calc() // I want this vale to increase along with i inside masterLoop()
};
setInterval(function() {
console.log(options.number);
}, 5000);
通常,在这种情况下,我将尝试使用return
来检索值,但是由于递增值位于setInterval内,因此无法找到解决方案作用域不适用于return
。
以下是一个示例:
function calc() {
var foo = 1;
setInterval(function() {
var foo = foo + 1;
}, 1000);
return foo; // the incrementing value of foo is not available outside the scope of setIterval, so this won't work. The return also won't work inside setInterval.
}
var optionsConstant = {
maxVolume: 10
};
var options = {
maxVolume: optionsConstant.maxVolume + calc() // I want calc() to be able to increment along with foo in the setInterval above.
};
setInterval(function() {
var maxVolume = options.maxVolume;
console.log('maxVolume: ' + maxVolume);
}, 5000);
答案 0 :(得分:2)
第二次尝试,您可以使calc
为立即调用的函数表达式(提供闭包),并在其中返回可以访问foo
的函数。
然后,为了保留options.maxVolume
的最终语法,您应该将该属性定义为getter,以便实际上它在被访问时将执行一些代码,并调用calc()
:
var calc = (function () { // create closure for foo
var foo = 1;
setInterval(function() {
foo = foo + 1; // remove var!
}, 100);
return function calc() { // return a function
return foo;
}
})();
var optionsConstant = {
maxVolume: 10
};
var options = {
get maxVolume() { // make it a getter
return optionsConstant.maxVolume + calc();
}
};
setInterval(function() {
var maxVolume = options.maxVolume;
console.log('maxVolume: ' + maxVolume);
}, 500);
答案 1 :(得分:1)
您可以在masterloop函数范围之外声明增量变量,以便其他函数可以在需要时访问它并读取其值吗?
您需要确保在适当的时候重新初始化它的值。
答案 2 :(得分:-1)
我认为您需要使用闭包。这是一个示例:
let returnI = (function masterLoop(i) {
setTimeout(function() {
++i;
masterLoopStage = i;
console.log('Stage is: ' + i);
return masterLoop(i);
}, 5000)
})(1);
function calc() {
number = returnI;
return number;
}
var options = {
number: calc()
};
setInterval(function() {
console.log(options.number);
}, 5000);