Cara menggunakan constructor function in javascript

Pada artikel tentang Penggunaan Class Typescript kita sudah sedikit membahas tentang constructor. Sekilas tentang constructor merupakan sebuah method yang akan dijalankan paling awal didalam sebuah class. Pada saat kita membahas tentang inherintance atau perwarisan kita juga menggunakan constructor terutama jika teman-teman perhatikan pada parent classnya. 

export class Kendaraan {
  merek: string;
  roda: number;

  constructor(smerek: any, sroda: number = 0) {
    this.merek = smerek;
    this.roda = sroda;
  }
}

Lalu sekarang pertanyaannya adalah bagaimana jika pada sub classnya kita ingin menggunakan constructor juga?. Di dalam pemrograman typescript masalah seperti ini dapat di selsaikan dengan super constructor. Artinya super constructor dapat mengambil parameter yang ada dalam contructor di parent classnya untuk dibantu menginisialisasikan di sub classnya. Sebagai contoh:

export class Mobil extends Kendaraan {
  namaMobil: string;

  constructor(snamaMobil: string, smerek: string, sroda: number = 0) {
    super(smerek, sroda);
    this.namaMobil = snamaMobil;
  }
}

Saat ini kita memiliki class mobil, dimana didalam class mobil kita memiliki property namaMobil, untuk menggunakan super constructor kita menggunakan keyword super dialam method super tersebut kita akan menginisialisikan parameter yang dibutuhkan parent classnya. Dengan mengimplementasikan block code diatas maka kita dapat melihat dan mengakses properti yang ada seperti biasa

let honda = new Mobil("Honda City", "honda", 4);
console.log(honda.namaMobil);
console.log(honda.roda);
console.log(honda.merek);

Setter Getter

Pada dasarnya Setter Getter merupakan sebuah method yang bertugas untuk mengisi data dan mengaksess atau mengambil data didalam sebuah object. Method ini banyak digunakan didalam konsep OOP ( Object Oriented Programming ). Dalam konsep encapsulation atau pembungkusan dimana semua property memiliki modifier private dalam hal inilah method setter getter digunakan. Ada beberapa keuntungan kenapa kedua method ini ada 

  • Data yang semakin aman, karena bersifat private
  • Kemudahan untuk mengontrol atribut dan method
  • fleksibelitas utnuk memperbaharui kode tanpa harus berdampak pada kode lain

Sebgai contoh penggunaan setter getter kita akan melihat block kode dibawah

export class Mobil extends Kendaraan {
  namaMobil: string;
  private NoMesin: number = 0;

  constructor(snamaMobil: string, smerek: string, sroda: number = 0) {
    super(smerek, sroda);
    this.namaMobil = snamaMobil;
  }

  set noMesin(sNoMesin: number) {
    this.NoMesin = sNoMesin;
  }

  get noMesin(): number {
    return this.NoMesin;
  }
}

Di dalam block kode diatas kita sudah memiliki class mobil dimana kita menambahkan satu property yaitu NoMesin yang bersifat private. Laku dalam pembuatan method setter kita mengguakan kata kunci set dan getter menggunakan kata kunci get. Lalu berikut adalah cara menginisialisasikannya

In JavaScript, when

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23,

     this.greet = function () {
        console.log('hello');
    }
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John
8 keyword is used in a constructor function,
// constructor function
function Person () {
    this.name = 'John',
    this.age = 23,

     this.greet = function () {
        console.log('hello');
    }
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John
8 refers to the object when the object is created. For example,

// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John

Hence, when an object accesses the properties, it can directly access the property as

// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
0.


JavaScript Constructor Function Parameters

You can also create a constructor function with parameters. For example,

// constructor function
function Person (person_name, person_age, person_gender) {

   // assigning  parameter values to the calling object
    this.name = person_name,
    this.age = person_age,
    this.gender = person_gender,

    this.greet = function () {
        return ('Hi' + ' ' + this.name);
    }
}


// creating objects
const person1 = new Person('John', 23, 'male');
const person2 = new Person('Sam', 25, 'female');

// accessing properties
console.log(person1.name); // "John"
console.log(person2.name); // "Sam"

In the above example, we have passed arguments to the constructor function during the creation of the object.

const person1 = new Person('John', 23, 'male');
const person2 = new Person('Sam', 25, 'male');

This allows each object to have different properties. As shown above,

// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
1 gives John

// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
2 gives Sam


Create Objects: Constructor Function Vs Object Literal

  • Object Literal is generally used to create a single object. The constructor function is useful if you want to create multiple objects. For example,
// using object literal
let person = {
    name: 'Sam'
}
// using constructor function
function Person () {
    this.name = 'Sam'
}

let person1 = new Person();
let person2 = new Person();
  • Each object created from the constructor function is unique. You can have the same properties as the constructor function or add a new property to one particular object. For example,
// using constructor function
function Person () {
    this.name = 'Sam'
}

let person1 = new Person();
let person2 = new Person();

// adding new property to person1
person1.age = 20;

Now this

// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
3 property is unique to
// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
4 object and is not available to
// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
5 object.

However, if an object is created with an object literal, and if a variable is defined with that object value, any changes in variable value will change the original object. For example,

// using object lateral
let person = {
    name: 'Sam'
}

console.log(person.name); // Sam

let student = person;

// changes the property of an object
student.name = 'John';

// changes the origins object property
console.log(person.name); // John

When an object is created with an object literal, any object variable derived from that object will act as a clone of the original object. Hence, any change you make in one object will also reflect in the other object.


Adding Properties And Methods in an Object

You can add properties or methods in an object like this:

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23
}

// creating objects
let person1 = new Person();
let person2 = new Person();

// adding property to person1 object
person1.gender = 'male';

// adding method to person1 object
person1.greet = function () {
    console.log('hello');
}

person1.greet();   // hello

// Error code
// person2 doesn't have greet() method
person2.greet();

Output

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23,

     this.greet = function () {
        console.log('hello');
    }
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John
0

In the above example, a new property

// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
6 and a new method
// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
7 is added to the
// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
4 object.

However, this new property and method is only added to

// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
4. You cannot access
// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
6 or
// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
7 from
// constructor function
function Person () {
    this.name = 'John',
}

// create object
const person1 = new Person();

// access properties
console.log(person1.name);  // John
5. Hence the program gives error when we try to access
// constructor function
function Person (person_name, person_age, person_gender) {

   // assigning  parameter values to the calling object
    this.name = person_name,
    this.age = person_age,
    this.gender = person_gender,

    this.greet = function () {
        return ('Hi' + ' ' + this.name);
    }
}


// creating objects
const person1 = new Person('John', 23, 'male');
const person2 = new Person('Sam', 25, 'female');

// accessing properties
console.log(person1.name); // "John"
console.log(person2.name); // "Sam"
3


JavaScript Object Prototype

You can also add properties and methods to a constructor function using a prototype. For example,

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23,

     this.greet = function () {
        console.log('hello');
    }
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John
1

To learn more about prototypes, visit JavaScript Prototype.


JavaScript Built-in Constructors

JavaScript also has built-in constructors. Some of them are:

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23,

     this.greet = function () {
        console.log('hello');
    }
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John
2

In JavaScript, strings can be created as objects by:

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23,

     this.greet = function () {
        console.log('hello');
    }
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John
3

In JavaScript, numbers can be created as objects by:

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23,

     this.greet = function () {
        console.log('hello');
    }
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John
4

In JavaScript, booleans can be created as objects by:

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23,

     this.greet = function () {
        console.log('hello');
    }
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John
5

Note: It is recommended to use primitive data types and create them in a normal way, such as

// constructor function
function Person (person_name, person_age, person_gender) {

   // assigning  parameter values to the calling object
    this.name = person_name,
    this.age = person_age,
    this.gender = person_gender,

    this.greet = function () {
        return ('Hi' + ' ' + this.name);
    }
}


// creating objects
const person1 = new Person('John', 23, 'male');
const person2 = new Person('Sam', 25, 'female');

// accessing properties
console.log(person1.name); // "John"
console.log(person2.name); // "Sam"
4,
// constructor function
function Person (person_name, person_age, person_gender) {

   // assigning  parameter values to the calling object
    this.name = person_name,
    this.age = person_age,
    this.gender = person_gender,

    this.greet = function () {
        return ('Hi' + ' ' + this.name);
    }
}


// creating objects
const person1 = new Person('John', 23, 'male');
const person2 = new Person('Sam', 25, 'female');

// accessing properties
console.log(person1.name); // "John"
console.log(person2.name); // "Sam"
5 and
// constructor function
function Person (person_name, person_age, person_gender) {

   // assigning  parameter values to the calling object
    this.name = person_name,
    this.age = person_age,
    this.gender = person_gender,

    this.greet = function () {
        return ('Hi' + ' ' + this.name);
    }
}


// creating objects
const person1 = new Person('John', 23, 'male');
const person2 = new Person('Sam', 25, 'female');

// accessing properties
console.log(person1.name); // "John"
console.log(person2.name); // "Sam"
6

You should not declare strings, numbers, and boolean values as objects because they slow down the program.


Note: In JavaScript, the keyword

// constructor function
function Person (person_name, person_age, person_gender) {

   // assigning  parameter values to the calling object
    this.name = person_name,
    this.age = person_age,
    this.gender = person_gender,

    this.greet = function () {
        return ('Hi' + ' ' + this.name);
    }
}


// creating objects
const person1 = new Person('John', 23, 'male');
const person2 = new Person('Sam', 25, 'female');

// accessing properties
console.log(person1.name); // "John"
console.log(person2.name); // "Sam"
7 was introduced in ES6 (ES2015) that also allows us to create objects. Classes are similar to constructor functions in JavaScript. To learn more, visit .

Apa itu constructor di javascript?

Constructor biasanya digunakan untuk inisialisasi nilai properti atau nilai variable tertentu. Constructor mempunyai parameter seperti juga fungsi. Nilai pada parameter tersebut diberikan pada waktu object dibuat dengan menggunakan keyword new.

Apakah peran dari constructor?

Constructor adalah member function khusus yang dijalankan secara otomatis pada saat sebuah object dibuat, yakni saat proses instansiasi.

Mengapa butuh constructor?

Constructor biasa digunakan untuk membuat proses awal dalam mempersiapkan objek, seperti memberi nilai awal kepada property, memanggil method internal dan beberapa proses lain yang digunakan untuk mempersiapkan objek.

Apa perbedaan antara constructor dan destructor?

Intinya constructor adalah sebuah method. Method yang akan dieksekusi saat pembuatan objek. Sementara untuk destructor adalah kebalikan dari constructor dan Java tidak memiliki destructor karena menggunakan metode gerbage collector.