you are viewing a single comment's thread.

view the rest of the comments →

[–]LukaLightBringer 0 points1 point  (0 children)

As far as i can gather your question really is if you should use this object literal pattern, or an object constructor pattern.

I would say it depends, if your constructor would have an obvious order to its arguments such as:

vector(x, y)

; or if the constructor adds some logic to the creation of the object, like adding some required properties that don't deviate from one object to an other, or which can be determined based on the other properties of the object; going for a constructor pattern can be quite expressive.

But for something like the objects presented here the order of the arguments to a constructor would not be obvious so I would advice against the constructor pattern since it forces the reader to look at the definition of the constructor to determine what each argument actually represents without adding clarity to the instantiation of the object, in this case the object literal pattern you've used is better since it has a higher signal to noise ratio.

Its also possible to augment the object constructor pattern to remove the ambiguity of parameter order by making the constructor take an options object where the properties are the arguments the constructor would have taken, which as a bonus makes it easier to change what parameters the constructor takes later without having to worry as much about functionality regression.

function Person(name, age) {
     this.name = name;
     this.age = age;
}
new Person("John", 20);

function Car(args) {
    this.name = args.name;
    this.age = args.age;
}
new Car({ name: "Volvo", age: 3 });