Fra*_*sca 0 javascript variables function
不知道我哪里出错了.
我有以下代码,每1-2秒在页面上创建一个"气泡",然后在6秒后销毁每个气泡.
代码通常工作正常,除了尽管被初始化bubbleID显示的变量undefined.
function startBubbleMachine(){
var bubbleID = 1;
setInterval(function makeBubble(bubbleID){
var wh = randomInt(143, 50);
console.log('making bubble number '+bubbleID); // this shows undefined
$('.wrapper').append('<div class="db-bubble db-bubble-'+bubbleID+'" style="transform:rotate('+randomInt(20, 1)+'deg);left:'+randomInt(100, 1)+'%;width:'+wh+'px;height:'+wh+'px;"></div>');
killBubble(bubbleID);
bubbleID++; // this doesn't seem to get used
}, randomInt(2000, 1000));
}
Run Code Online (Sandbox Code Playgroud)
我正在初始化bubbleID为1:
var bubbleID = 1;
Run Code Online (Sandbox Code Playgroud)
我正在传递bubbleID函数内部setInterval
setInterval(function makeBubble(bubbleID){
...
});
Run Code Online (Sandbox Code Playgroud)
然后我在该函数中递增它:
bubbleID++;
Run Code Online (Sandbox Code Playgroud)
我哪里错了?
您var bubbleID通过在匿名函数中包含一个类似命名的参数来隐藏变量.摆脱形式参数.
setInterval(function makeBubble( ){
// ^
Run Code Online (Sandbox Code Playgroud)
包括该参数名称不传递变量; 它只是说该函数需要传递一个参数.但是,没有必要这样做,因为该定时器函数中的代码可以bubbleID通过闭包"看到" 变量.
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |