Javascript: Constructor or Literal notation? -
this question more aimed @ developers professionally, , or work freelancers/in teams/for businesses/etc.
is using literal javascript notation more sought after constructor notation? matter kind of notation use when writing javascript? employers care, or there more professional notation?
literal notation
var snoopy = { species: "beagle", age: 10 };
constructor notation
var buddy = new object(); buddy.species = "golden retriever"; buddy.age = 5;
if literal notation work situation, more compact , preferred on second method. there types of properties cannot expressed in literal notation must set manually assigning property in second scheme.
for example if want refer other property on object, can't in literal definition have property assignment on constructed object.
var snoopy = { species: "beagle", age: 10 }; snoopy.peopleage = convertdogagetopeopleage(snoopy.age);
what refer "constructor notation" not people how use constructor initialize object. usually, constructor used when want able make more 1 of given type of object such as:
function animal(species, age) { this.species = species; this.age = age; } var buddy = new animal("golden retriever", 5); console.log(buddy.species); // "golden retriever" var snoopy = new animal("beagle", 10); console.log(snoopy.species); // "beagle"
what have called constructor way create new empty object. both of these same thing:
var x = {}; var y = new object();
again, first way preferred because it's more compact , potentially easier interpreter optimize , javascript community seems have decided literal declaration of {}
or []
preferred unless there explicit reason have use new xxxx()
form.
Comments
Post a Comment