简体   繁体   English

在回调中访问全局定义的变量?

[英]Accessing a globally defined variable inside a callback?

I am writing a three.js application and need to access a variable called camera , because whenever I click a button I want to move the camera up and down.我正在编写一个 three.js 应用程序,需要访问一个名为camera的变量,因为每当我单击一个按钮时,我都想上下移动相机。

However, my buttons are nested callbacks and I am wondering how can I accessing the variable within the callbacks?但是,我的按钮是嵌套回调,我想知道如何访问回调中的变量?

eg例如

    let camera = ...
    let circles = document.querySelectorAll('circle');
    circles.forEach(function(c){
        c.onclick = function(e){
            circles.forEach(function(circle){
                circle.classList.remove('active');
                circle.classList.add('disabled');
            });
            e.target.classList.add('active');
            e.target.classList.remove('disabled');
            if (e.target.id === "example"){
                camera.position.set(0,0,0) //camera not defined
            }
            debugger;
        }
    });

I am a little confused why I can access the circles varaible at the debugger point, however it keeps saying camera is undefined.我有点困惑为什么我可以在调试器点访问circles变量,但是它一直说camera未定义。

Just guessing, maybe because it's not used it got optimized away?只是猜测,也许是因为它没有被使用它被优化掉了? Try to do something with camera, print its name or whatever.尝试用相机做一些事情,打印它的名字或其他什么。 Then see if it's available in debug.然后看看它是否在调试中可用。

you can't access let variable inside.你不能访问 let 里面的变量。 visit below URL it'll help.访问下面的 URL 它会有所帮助。

https://stackoverflow.com/a/58735690/10627591 https://stackoverflow.com/a/58735690/10627591

If you want to access that variable declared it var keyword.如果要访问声明它的变量 var 关键字。

Ok, I am at a loss for words.好吧,我无语了。

If I try to use the variable, eg camera.position.set(0,0,0) inside where I want to use it, I can print the variable inside the console.如果我尝试在我想使用它的地方使用变量,例如camera.position.set(0,0,0) ,我可以在控制台中打印变量。

If I do not use it, then I get an error.如果我不使用它,则会出现错误。

The problem was me trying to debug and write tests first, before actually writing it.问题是我在实际编写测试之前先尝试调试和编写测试。

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

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