Javascript函数变量突然变得不确定? [英] Javascript function variable all of a sudden becomes undefined?

查看:56
本文介绍了Javascript函数变量突然变得不确定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是最奇怪的事情。我的代码如下:

this is the weirdest thing. My code is below:

function menuSwipe(init){
    dojo.query('div.fill div.container div.menu div.group ul').forEach(function(item){
        dojo.fx.wipeOut({
            node: item,
            duration: 1
        }).play();
        dojo.query('li', item).forEach(function(childrenItem){
            if (dojo.hasClass(childrenItem, 'active')) 
                childrenItem.parentNode.className = 'items active';
        });
        if (item.className == 'items active') {

            dojo.query('div.category', item.parentNode).forEach(function(parentItem){
                setTimeout(function(){
                    menuOpen(parentItem, init);
                    doGrayscale(parentItem);
                }, 100);
            });
        }
    });
}

基本上 init 直到它进入if (item.className =='items active')条件中。之后,它变为未定义。我正在设置一个布尔值。只要它在 if(item.className ==‘items active’)之前,它将保留其值。我没有理由这样做。我尝试做 this.init = 并将其设置为 var init = init 。有谁知道或有某种方法可以在整个功能中保留其价值?它不是init命名的,我尝试使用不同的名称,但它仍然执行相同的操作。

Basically init stays in memory until it goes in the if (item.className == 'items active') conditional. After that it becomes undefined. It is a boolean value that I am setting. As long as it is before if (item.className == 'items active') it will retain its value. I have no reason why its doing this. I have tried to do this.init = and setting it as var init = init. Does anyone know or is there some way I can retain its value all throughout the function? Its not the init naming, I have tried a different name and it still does the same thing.

谢谢,
达伦

推荐答案

问题是函数完成后超时正在运行,因此超时运行时parentItem变量已超出范围。

The problem is that the timeout is running after the function has completed, so the parentItem variable has gone out of scope when the timeout runs.

在该范围内创建一个局部变量,以便为超时函数创建一个闭包。这样,每次迭代都有自己的变量:

Create a local variable in that scope, so that a closure is created for the timeout function. That way each iteration has it's own variable:

dojo.query('div.category', item.parentNode).forEach(function(parentItem){
  var itemCopy = parentItem;
  window.setTimeout(function(){
    menuOpen(itemCopy, init);
    doGrayscale(itemCopy);
  }, 100);
});

这篇关于Javascript函数变量突然变得不确定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆