Videos
Computed property names are supported in ECMAScript2015:
var name = 'key';
var value = 'value';
var o = {
[name]: value
};
console.log("o as json : " + JSON.stringify(o));
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
Prior to ECMAScript 2015 (ed 6), an object literal (ECMAScript calls it an "object initializer") key must be one of:
- IdentifierName
- StringLiteral
- NumericLiteral
So you couldn't use an expression as the key in an initialiser. This was changed as of ECMAScript 2015 (see below). You could use an expression with square bracket notation to access a property, so to set the properties with an expression you had to do:
var required = { directories : {}};
required.directories[this.applicationPath] = "Application " + this.application + " does not exists";
required.directories[this.applicationPath + "/configs"] = "Application config folder does not exists";
...
and so on. Since this.applicationPath is reused a lot, better to store a reference to help with performance and cut down the amount of code:
var a = this.applicationPath;
var required = { directories : {}};
var rd = required.directories;
rd[a] = "Application " + this.application + " does not exists";
rd[a + "/configs"] = "Application config folder does not exists";
...
Edit
As of ECMAScript 2015 (ed 6), object initializers can have computed keys using:
[expression]: value
There is also shorthand syntax for property and method names.
See MDN: Object Initializer or ECMAScript Object Initializer.
Syntactically, the change is very simple :
var bob = {
age: 30,
setAge: function (newAge) {
bob.age = newAge;
}
};
But as you can see, there's a problem : as in your code it uses the external bob variable so this wouldn't work if you change the value of the bob variable.
You can fix that with
var bob = {
age: 30,
setAge: function (newAge) {
this.age = newAge;
}
};
Note that at this point you should check whether what you need isn't, in fact, a class, which would bring some performance improvements if you have several instances.
Update: ECMAScript 6 now allows methods to be defined the same way regardless of whether they are in an object literal:
var bob = {
age: 30,
setAge (newAge) {
this.age = newAge;
}
};
Its nothing different and as easy as
var bob = {
age: 30,
setAge: function( newAge ) {
this.age = newAge;
}
};
Alternatively, you can create a real setter function either by invoking Object.defineProperty() or as simple as
var bob = {
age: 30,
firstName: 'j',
lastName: 'Andy',
set setName( newName ) {
var spl = newName.split( /\s+/ );
this.firstName = spl[ 0 ];
this.lastName = spl[ 1 ];
}
}
Where you could go like
bob.setName = "Thomas Cook"; // which sets firstName to "Thomas" and lastName to "Cook"