javascript 删除全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7771699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:15:29  来源:igfitidea点击:

remove global variable

javascript

提问by Ido Tamir

I use limejsand I declare a function like:

我使用limejs并声明一个函数,如:

function up(){
   var pos = global.getPosition();
   pos.x += 2;
   global.setPosition(pos);
}

and call it using

并调用它使用

lime.scheduleManager.schedule(up,global);

How do I get rid of the global variable?

如何摆脱全局变量?

采纳答案by usoban

Since second parameter to scheduleis context object and you pass globalto it, you could write the function as

由于第二个参数 toschedule是上下文对象并且您传递global给它,因此您可以将函数编写为

function up(){
   var pos = this.getPosition();
   pos += 2;
   this.setPosition(pos);
}

If that is really what you're asking for.

如果这真的是你所要求的。

If you only need to delete the variable, you can set it to null. Operator deleteis intended for deleting object properties, not unsetting variables.

如果只需要删除变量,可以设置为null。运算符delete旨在删除对象属性,而不是取消设置变量。

回答by hvgotcodes

you can always delete a property on an object like so (note that global variables are really on window, at least in browser javascript)

您总是可以像这样删除对象上的属性(请注意,全局变量确实是 on window,至少在浏览器 javascript 中)

delete window.global;

delete window.global;

if you then try to access your variable, you will get a Reference error. Be careful, because if your schedulecall invokes the method later, and it depends on global, it will be gone. Might be better just to use a local variable (with var)

如果您随后尝试访问您的变量,您将收到一个引用错误。小心,因为如果你的schedule调用稍后调用该方法,并且它依赖于全局,它就会消失。仅使用局部变量可能会更好(使用var

enter image description here

在此处输入图片说明

回答by josh3736

If you're not referencing that function anywhere else, why not just:

如果您没有在其他任何地方引用该函数,为什么不只是:

lime.scheduleManager.schedule(function (){ 
   var pos = global.getPosition(); 
   pos.x += 2; 
   global.setPosition(pos); 
}, global); 

回答by Juan Mendes

If you mean mark it so it can be garbage collected, you can just set the reference to null. If there are no other references, the object will be gc'd next time the gc kicks in.

如果你的意思是标记它以便它可以被垃圾收集,你可以将引用设置为空。如果没有其他引用,该对象将在下次 gc 启动时被 gc。

回答by jtfairbank

In regular javascript it would be:

在常规 javascript 中,它将是:

delete global.myVar

or

或者

delete pos

Not 100% sure if this will work in limejs (never used it) but worth a try.

不能 100% 确定这是否适用于limejs(从未使用过),但值得一试。