Is it bad practice to not assign a new object to a variable?

前端 未结 5 714
孤街浪徒
孤街浪徒 2020-12-28 18:56

Is it bad javascript practice to not assign a newly created object to a variable if you\'re never going to access it?

For example:

for(var i=0;i

        
5条回答
  •  灰色年华
    2020-12-28 19:47

    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.

提交回复
热议问题