问题描述
如果您永远不会访问变量,则不将新创建的对象分配给变量是不好的JavaScript做法吗?
Is it bad javascript practice to not assign a newly created object to a variable if you're never going to access it?
例如:
for(var i=0;i<links.length;i++){
new objectName(links[i]);
}
同样,我不会访问它,因此不需要变量来引用它.
And again, I won't be accessing it, so there's no need for a variable to reference it.
推荐答案
如果您不访问它,但它仍然有用,则表明构造函数本身具有明显的副作用.一般来说,这是个坏主意.
If you're not accessing it but it's still useful, that suggests that the constructor itself has visible side effects. Generally speaking, that's a bad idea.
如果您根本不调用构造函数,将会发生什么变化?
What would change if you didn't call the constructor at all?
如果您的构造函数对全局状态有所影响,那会让我感到非常糟糕.另一方面,您可以仅出于验证目的而使用它-即,如果构造函数返回而没有引发异常,则可以.并不是很糟糕,但是如果是这样的话,一种单独的验证方法将使事情变得更加清晰.
If your constructor is doing something to the global state, that strikes me as very bad. On the other hand, you could be using it just for the sake of validation - i.e. if the constructor returns without throwing an exception, it's okay. That's not quite so bad, but a separate method for validation would make things a lot clearer if that's the case.
这篇关于不将新对象分配给变量是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!