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

前端 未结 5 684
孤街浪徒
孤街浪徒 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:35

    That’s absolutely fine if you don’t need to use it again. But we need to explain why.

    An object can continue to do something, even if you don't have a reference to it (like other suggested, an animation, a listener, etc.)

    Who think this is odd, should reflect on the alternatives before say this is not fine:

    • Maybe someone forget to assign the object to a variable? Maybe he made an even worse mistake: he forget to use it later. Is it reasonable? Is it Odd?
    • Is new objectName().start() more clear? maybe. But if you always need to call start() immediately after creation to make the object useful, it is better to include the start() in the costructor. This way you can't forget to do it.
    • If you can do it with a static method, without constructors inside, then the real question is: Why do you have an Object? a simple function should be enough.
    • If you create a static method only to create new Object, from one side maybe is more clear that it will do something (but you should anyway assume that a constructor can do something, this is a fact) on the other side is less clear that something can continue acting after the call. If you are not in the previous case (no creation of objects), maybe it is better to emphatize on the creation of something using a constructor. But what is more clear is subjective and can be pointless to argue more.

    A good Object name can clarify or suggest that the object will do something, after creation.

    Examples:

    new Baby() is supposed to start to cry, sometimes. And he will live even if you don't tell him to to something.

    new AutoRegisteringListener(); Really need to explain what will happen when you create such object? are you really surprised that this listener will register itself to some events?

    In my opinion, the point is to think in object-oriented way, instead of thinking only in functional way: objects can have behaviour. This is what they are designed for, among other things.

提交回复
热议问题