JavaScript-使用新关键字的标准 [英] JavaScript - standard in using new key word
问题描述
这是一个与内存使用和"new"关键字有关的问题.我需要您的建议和偏爱,以便在本地方法中使用新"字词.
This is a question which is related to memory usage and "new" keyword. I need your suggesions and preferences for using "new" in local methods.
get: function ()
{
var get = new Ajax.Updater('resourceList',
"url",
{
method: 'POST',
onComplete: this._onComplete.bind(this)
});
}
在上面的代码中,我将对象分配给一个在任何地方都不使用的局部变量,我也可以通过以下方式编写代码
In the above code, I am assigning the object to a local variable which is not used anywhere, I can write the code in the following way also
get: function ()
{
new Ajax.Updater('resourceList',
"url",
{
method: 'POST',
onComplete: this._onComplete.bind(this)
});
}
这里我没有将对象分配给任何变量.
Here I am not assigning the object to any variable.
我现在有点困惑.分配变量还是不分配变量哪个更好?如果我在局部方法作用域之后分配一个变量,则该对象将从内存中删除,但是如果我不分配,将发生什么?垃圾收集会处理吗?最好的方法是什么?就我个人而言,我更喜欢分配一个变量.那是对的吗?如果我不分配给变量,什么时候该对象会被破坏?
I am little confused now. Which way is better, assigning to a variable or not assigning to a variable? If I assign to a variable after the local method scope the object will be taken off from memory, but if I don't assign what will happen? Will it be taken care of by garbage collection? What is Which is the best way of doing it ? Personally I prefer to assign to a variable; is that correct? when will the object get destroyed if I am not assigning to a variable?
推荐答案
JavaScript垃圾收集器将处理超出范围的项目,并且这些项目不再可访问;无论您是否将Ajax.Updater
对象分配给变量,都将如此.
JavaScripts garbage collector will process items as they fall out of scope, and are no longer reachable; this will be true for your Ajax.Updater
object regardless of whether you assign it to a variable or not.
关于是否应将其分配给变量? 我不会.很明显,没有别的东西再次引用该对象.如果将其分配给变量,人们将开始寻找使用该变量的位置.
So as to whether you should assign it to a variable or not? I wouldn't. It makes it clear that nothing else refers to that object again. If you assign it to a variable, people will start looking to see where that variable is used.
垃圾收集器非常聪明且聪明.您几乎不必担心垃圾收集器是否会捡拾东西.在99.99999999%的情况下会.
The garbage collector is very clever and intelligent. You seldom need to worry about whether the garbage collector will pick up something or not. In 99.99999999% cases, it will.
这篇关于JavaScript-使用新关键字的标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!