简体   繁体   English

尽管变量已初始化并传递给函数,但未定义

[英]Variable is undefined despite being initialised and passed to function

Not sure where I have gone wrong. 不知道我哪里出问题了。

I have the following code which creates a "bubble" on the page every 1-2 seconds, and then destroys each bubble after 6 seconds. 我有以下代码,该代码每1-2秒在页面上创建一个“气泡”,然后在6秒后销毁每个气泡。

The code generally works fine except for the variable bubbleID which shows as undefined despite being initialised. 该代码通常可以正常工作,但变量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));
    }

I'm initialising the bubbleID to 1: 我正在将bubbleID初始化为1:

var bubbleID = 1;

I'm then passing the bubbleID in the function within the setInterval 然后,我在setInterval中的函数中传递bubbleID

setInterval(function makeBubble(bubbleID){
    ...
});

And then I'm incrementing it within that function: 然后在该函数中增加它:

bubbleID++;

Where am I going wrong? 我要去哪里错了?

You're hiding the var bubbleID variable by including a like-named parameter in the anonymous function. 通过在匿名函数中包含一个名称相同的参数,可以隐藏var bubbleID变量。 Get rid of the formal parameter. 摆脱形式参数。

setInterval(function makeBubble( ){
//                              ^

Including that parameter name does not pass the variable; 包括该参数名称不传递变量; it simply says that the function expects a parameter to be passed. 它只是说函数期望参数被传递。 There's no need for that, however, because the code in that timer function can "see" the bubbleID variable through closure. 但是, bubbleID ,因为该计时器函数中的代码可以通过关闭“看到” bubbleID变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM