ES6 brings a new syntax for object definitions that may baffle JavaScript programmers a little. I am not sure if we really need these features, but they are there and will be used, so we have to learn them. Most irritating may be the "computed property names".
ES6 New Object Syntax Tests
Postface
Having real maps, supported by the language itself, is a great relief. Nevertheless still immutability is missing. We would need it for both object-functions (would make them real methods) and properties (constants within objects).
The object testObject
is constructed in a different way than
it was done in JavaScript. Its two functions foo
and bar
are put onto the object without the use of colons,
not even the keyword function
is used.
This gives ES6 a concise and elegant object construction.
Mind that still we do not have immutable object functions!
The object testObject
is constructed without the use of colons.
Just make sure that variables of same name as the object properties exist before,
and you can copy them into the object. Changing a variable value afterwards
does not affect the according object property.
Mind that still we do not have immutable object properties!
In JavaScript it was not possible to have an expression on the left side of a property definition.
In ES6 it is. We need to get used to that: the square brackets here are not related to an array!
Here, an object is built by first defining a property foo
, in a traditional way using colon.
Then, on the left side, there is a square-bracket expression containing a function call.
Whatever the outcome of that expression is will be taken to be the property identifier.
The function computePropertyName
simply returns the given parameter.
Mind that we still have just strings on the key-side of an ES6 object, no numbers or objects!
In JavaScript, objects were maps and maps were objects.
Just that the map-key was always stringified, because it had to be a property name.
In ES6 we have maps that can have a non-string as key.
As key for PI we define an object called piKey
.
Then we construct a map and set the key-value pair into it.
Reading the first key from the map shows that it is piKey
,
not its stringification.
Mind that you can not put key-value pairs into a Map
with the square-bracket notation: map[piKey] = 3.14159, this does NOT work!
Keine Kommentare:
Kommentar veröffentlichen