我希望能够增加/更改对象内参数的值。我希望通过访问在另一个函数内递增的变量的值来更改该值。
下面的示例代码显示了我正在尝试做的事情。我希望 options.number
随着 masterLoop
内的 i
的增加而增加。
我知道 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);
最佳答案
进行第二次尝试时,您可以使 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);
关于javascript - 如何使用函数增加对象中参数的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55326972/