Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

前端 未结 8 1886
无人共我
无人共我 2020-11-27 08:59

So far I saw three ways for creating an object in JavaScript. Which way is best for creating an object and why?

I also saw that in all of these examples the keyword

8条回答
  •  无人及你
    2020-11-27 09:37

    There is no "best way" to create an object. Each way has benefits depending on your use case.

    The constructor pattern (a function paired with the new operator to invoke it) provides the possibility of using prototypal inheritance, whereas the other ways don't. So if you want prototypal inheritance, then a constructor function is a fine way to go.

    However, if you want prototypal inheritance, you may as well use Object.create, which makes the inheritance more obvious.

    Creating an object literal (ex: var obj = {foo: "bar"};) works great if you happen to have all the properties you wish to set on hand at creation time.

    For setting properties later, the NewObject.property1 syntax is generally preferable to NewObject['property1'] if you know the property name. But the latter is useful when you don't actually have the property's name ahead of time (ex: NewObject[someStringVar]).

    Hope this helps!

提交回复
热议问题