html
html
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
<!--
[JavaScript:] How to create objects
In JavaScript, objects provide a way for us to store, manipulate, and send data over the network.
Here, let us only focus on the various ways in which JavaScript allows us to create objects.
In JavaScript, think of objects as a collection of 'key:value' pairs. This brings to us the first and most popular way we create objects in JavaScript.
1. Creating objects using object literal syntax
This is really simple. All you have to do is throw your key value pairs separated by ':' inside a set of curly braces( {} ) and your object is ready to be served (or consumed), like below:
var person = {
firstName : 'testFirstName',
lastName : 'testLastName'
};
This is the simplest and most popular way to create objects in JavaScript.
2. Creating objects using the 'new' keyword
Enter to Rename, Shift+Enter to Preview
css
css
1
2
3
body {
}
Enter to Rename, Shift+Enter to Preview
js
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
console.log(
" #How to create objects\n");
/*
console.log(
"\n 1. Using object literal syntax\n");
var person = {
firstName : 'testFirstName',
lastName : 'testLastName'
};
*/
console.log(
" 3. Using Object.create()\n");
let orgObject = {
company: 'SoloLearn'
}
let employee = Object.create(orgObject,
{
name: {
value: '@Dan&Jel'
}
});
console.log(employee.name);
Enter to Rename, Shift+Enter to Preview
BROWSER
Console
Run