Program JavaScript untuk Membuat Objek dengan Cara Berbeda

0
(0)

Anda dapat membuat objek dengan tiga cara berbeda:

  1. Menggunakan objek literal
  2. Dengan membuat instance Object secara langsung
  3. Dengan menggunakan fungsi konstruktor

Contoh 1: Menggunakan objek literal

// program to create JavaScript object using object literal
const person = { 
    name: 'John',
    age: 20,
    hobbies: ['reading', 'games', 'coding'],
    greet: function() {
        console.log('Hello everyone.');
    },
    score: {
        maths: 90,
        science: 80
    }
};

console.log(typeof person); // object

// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);

Keluaran

object
John
reading
Hello everyone.
90

Dalam program ini, kami telah membuat sebuah objek bernama orang.

Anda dapat membuat objek menggunakan literal objek. Objek yang digunakan secara literal { } untuk membuat objek secara langsung.

Sebuah objek dibuat dengan a kunci: nilai pasangan.

Anda juga dapat mendefinisikan fungsi, array, dan bahkan objek di dalam objek. Anda dapat mengakses nilai objek menggunakan titik . notasi.


Sintaks untuk membuat objek menggunakan instance dari objek adalah:

const objectName = new Object();

Contoh 2: Buat Objek menggunakan Contoh Objek Secara Langsung

// program to create JavaScript object using instance of an object
const person = new Object ( { 
    name: 'John',
    age: 20,
    hobbies: ['reading', 'games', 'coding'],
    greet: function() {
        console.log('Hello everyone.');
    },
    score: {
        maths: 90,
        science: 80
    }
});

console.log(typeof person); // object

// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);

Keluaran

object
John
reading
Hello everyone.
90

Di sini, new kata kunci digunakan dengan Object() Misalnya untuk membuat objek.


Contoh 3: Buat objek menggunakan Constructor Function

// program to create JavaScript object using instance of an object

function Person() {
    this.name = 'John',
    this.age = 20,
    this.hobbies = ['reading', 'games', 'coding'],
    this.greet = function() {
        console.log('Hello everyone.');
    },
    this.score = {
        maths: 90,
        science: 80
    }

}

const person = new Person();

console.log(typeof person); // object

// accessing the object value
console.log(person.name);
console.log(person.hobbies[0]);
person.greet();
console.log(person.score.maths);

Keluaran

object
John
reading
Hello everyone.
90

Dalam contoh di atas, file Person() fungsi konstruktor digunakan untuk membuat objek menggunakan new kata kunci.

new Person() membuat objek baru.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.