-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobj_literal_syntax.js
103 lines (84 loc) · 1.85 KB
/
obj_literal_syntax.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Object property initializer shorthand.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer}
*/
// example 1
function createMachine(name, age) {
return {
name: name,
age: age
};
}
// alternative of example 1
function _createMachine(name, age) {
return {
name,
age
};
}
// example 2
let hello = 'hello',
world = 'world';
const helloWorld = {
hello: hello,
age: world
};
// alternative of example 2
let _hello = 'hello',
_world = 'world';
const _helloWorld = {
_hello,
_world
};
/**
* Computed property names.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names}
*/
// example 1
let title = 'machine one';
let machine = {
[title]: 'abc-1',
'machine hour': 1000
};
// logging the machine object
console.log(machine);
console.log(machine[title]);
console.log(machine['machine hour']);
// example 2
let prefix = 'machine';
let _machine = {
[prefix + ' name']: 'abc-1',
[prefix + ' hour']: 1000
};
// logging the _machine object
console.log(_machine);
console.log(_machine[prefix + ' name']);
console.log(_machine[prefix + ' hour']);
console.log(_machine['machine name']);
console.log(_machine['machine hour']);
/**
* Concise method syntax.
* @see {@link https://www.demo2s.com/javascript/javascript-object-concise-method-syntax.html}
*/
// example 1
let server = {
name: 'server-one',
restart: function () {
console.log('The ' + this.name + ' is restarting...');
}
};
// alternative of example 1
let _server = {
name: 'server-one',
restart() {
console.log('The ' + this.name + ' is restarting...');
}
};
// example 2
let person = {
name: 'John',
'sayName'() {
console.log('My name is ' + this.name);
}
};
person['sayName'](); // object_name[property_name]()