When should I automatically create an object even if `new` is forgotten?

前端 未结 4 635
無奈伤痛
無奈伤痛 2020-11-30 11:05

Let us say I have the following object constructor:

function Foo(bar) {
    this.bar = bar;
}

If I run the function in the global scope wit

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 11:49

    While I don't have anything against that style, I would not personally use it just to be consistent. Sure, I can make all my constructors like this but it would seem like a lot more code to write.

    If I'm worried about accidentally invoking a constructor without new, I would rather use JSHint to warn me about it. See http://www.jshint.com/docs/options/#newcap.

提交回复
热议问题