Is JavaScript's “new” keyword considered harmful?

前端 未结 12 2059
情书的邮戳
情书的邮戳 2020-11-21 23:18

In another question, a user pointed out that the new keyword was dangerous to use and proposed a solution to object creation that did not use new.

12条回答
  •  长发绾君心
    2020-11-21 23:48

    Javascript being dynamic language there a zillion ways to mess up where another language would stop you.

    Avoiding a fundamental language feature such as new on the basis that you might mess up is a bit like removing your shiny new shoes before walking through a minefield just in case you might get your shoes muddy.

    I use a convention where function names begin with a lower case letter and 'functions' that are actually class definitions begin with a upper case letter. The result is a really quite compelling visual clue that the 'syntax' is wrong:-

    var o = MyClass();  // this is clearly wrong.
    

    On top of this good naming habits help. After all functions do things and therefore there should be a verb in its name whereas classes represent objects and are nouns and adjectives with no verb.

    var o = chair() // Executing chair is daft.
    var o = createChair() // makes sense.
    

    Its interesting how SO's syntax colouring has interpretted the code above.

提交回复
热议问题