Reputation: 3117
Can additional object properties in coffeescript/javascript be added dynamically to an existing object?
For example:
var fred = { name: "Fred", species: "Sub-Human" };
Now later, for example, I want to add college major to get this:
{ name: "Fred", species: "Sub-Human", major: "Computer Science" }
And... how does this affect, or does it affect performance?
Upvotes: 1
Views: 596
Reputation: 1075925
Sure, JavaScript objects are completely dynamic.
You can use dot notation with a property name literal:
fred.major = "Computer Science";
or brackets notation with a property name string:
fred["major"] = "Computer Science";
Literals can be optimized more by the JavaScript engine, strings can be the result of any expression (so, fred["m" + "ajo" + "r"] = ...
would work) and can include characters (like spaces — yes, really —) that you can't use in a property name literal.
I suggest working through some basic JavaScript tutorials (if you want to learn JavaScript) or CoffeeScript tutorials (if you want to learn CoffeeScript).
Upvotes: 4
Reputation: 13304
Yes;
fred["major"] = "Computer Science";
All properties on an object can be accessed by using square brackets and the property name. This method also allows you to set new properties.
fred.major = "Computer Science";
This will also work fine.
Upvotes: 2