EN
JavaScript - object constructors
0 points
In this article, we would like to show you how to use object constructors in JavaScript.
Quick solution:
xxxxxxxxxx
1
function User(id, name, age) {
2
this.id = id;
3
this.name = name;
4
this.age = age;
5
}
6
7
const user = new User(1, 'Tom', 23);
Note:
The constructor functions schould be named with a capital first letter.
In this section, we create use two different ways to use a constructor.
To create user object, we need to call the constructor function with the new
keyword.
xxxxxxxxxx
1
// create constructor
2
function User(id, name, age) {
3
this.id = id;
4
this.name = name;
5
this.age = age;
6
}
7
8
// usage example
9
const user1 = new User(1, 'Tom', 23);
10
const user2 = new User(2, 'Kate', 25);
11
12
console.log(JSON.stringify(user1)); // {"id":1,"name":"Tom","age":23}
13
console.log(JSON.stringify(user2)); // {"id":2,"name":"Kate","age":25}
ES6 intorduces class
keyword.
xxxxxxxxxx
1
class User {
2
constructor(id, name, age) {
3
this.id = id;
4
this.name = name;
5
this.age = age;
6
}
7
}
8
9
const user1 = new User(1, 'Tom', 23);
10
const user2 = new User(2, 'Kate', 25);
11
12
console.log(JSON.stringify(user1)); // {"id":1,"name":"Tom","age":23}
13
console.log(JSON.stringify(user2)); // {"id":2,"name":"Kate","age":25}