Languages
[Edit]
EN

JavaScript - object constructors

0 points
Created by:
cory
286

In this article, we would like to show you how to use object constructors in JavaScript.

Quick solution:

function User(id, name, age) {
    this.id = id;
    this.name = name;
    this.age = age;
}

const user = new User(1, 'Tom', 23);

Note:

The constructor functions schould be named with a capital first letter.

 

Practical examples

In this section, we create use two different ways to use a constructor.

1. Function based constructor

To create user object, we need to call the constructor function with the new keyword.

// ONLINE-RUNNER:browser;

// create constructor
function User(id, name, age) {
    this.id = id;
    this.name = name;
    this.age = age;
}

// usage example
const user1 = new User(1, 'Tom', 23);
const user2 = new User(2, 'Kate', 25);

console.log(JSON.stringify(user1));  // {"id":1,"name":"Tom","age":23}
console.log(JSON.stringify(user2));  // {"id":2,"name":"Kate","age":25}

2. Class based construtor

ES6 intorduces class keyword.

// ONLINE-RUNNER:browser;

class User {
  	constructor(id, name, age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

const user1 = new User(1, 'Tom', 23);
const user2 = new User(2, 'Kate', 25);

console.log(JSON.stringify(user1));  // {"id":1,"name":"Tom","age":23}
console.log(JSON.stringify(user2));  // {"id":2,"name":"Kate","age":25}

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join