1var o = {}; // Creates a new object
2
3// Example of an object property added
4// with defineProperty with a data property descriptor
5Object.defineProperty(o, 'a', {
6 value: 37,
7 writable: true,
8 enumerable: true,
9 configurable: true
10});
11// 'a' property exists in the o object and its value is 37
12
13// Example of an object property added
14// with defineProperty with an accessor property descriptor
15var bValue = 38;
16Object.defineProperty(o, 'b', {
17 // Using shorthand method names (ES2015 feature).
18 // This is equivalent to:
19 // get: function() { return bValue; },
20 // set: function(newValue) { bValue = newValue; },
21 get() { return bValue; },
22 set(newValue) { bValue = newValue; },
23 enumerable: true,
24 configurable: true
25});
26o.b; // 38
27// 'b' property exists in the o object and its value is 38
28// The value of o.b is now always identical to bValue,
29// unless o.b is redefined
30
31// You cannot try to mix both:
32Object.defineProperty(o, 'conflict', {
33 value: 0x9f91102,
34 get() { return 0xdeadbeef; }
35});
36// throws a TypeError: value appears
37// only in data descriptors,
38// get appears only in accessor descriptors
39
1// using __proto__
2var obj = {};
3var descriptor = Object.create(null); // no inherited properties
4descriptor.value = 'static';
5
6// not enumerable, not configurable, not writable as defaults
7Object.defineProperty(obj, 'key', descriptor);
8
9// being explicit
10Object.defineProperty(obj, 'key', {
11 enumerable: false,
12 configurable: false,
13 writable: false,
14 value: 'static'
15});
16
17// recycling same object
18function withValue(value) {
19 var d = withValue.d || (
20 withValue.d = {
21 enumerable: false,
22 writable: false,
23 configurable: false,
24 value: value
25 }
26 );
27
28 // avoiding duplicate operation for assigning value
29 if (d.value !== value) d.value = value;
30
31 return d;
32}
33// ... and ...
34Object.defineProperty(obj, 'key', withValue('static'));
35
36// if freeze is available, prevents adding or
37// removing the object prototype properties
38// (value, get, set, enumerable, writable, configurable)
39(Object.freeze || Object)(Object.prototype);
40
1There might not seem to be a difference with 'color' but consider:
2
3element.style.backgroundColor = 'blue' // works
4element.style['backgroundColor'] = 'blue' // works
5element.style['background-color'] = 'blue' // does not work
6
7element.style.setProperty('background-color','blue') // works
8element.style.setProperty('backgroundColor','blue') // does not work