Object.create() method

Kali ini ada yang menarik dari method Object.create(). Fungsi ini dapat kita gunakan untuk membuat sebuah object dari object prototype yang lain. Contoh penggunaan seperti ini:

var RootObject = {ui : {root : { }}}</p><p>var x = Object.create(RootObject);x.ui.root = “xxx”;console.log(“x obj : “, x.ui.root);

Kode di atas akan menghasilkan output

x obj : xxx

Kita coba buat object baru dengan kode berikut

var x = Object.create(RootObject);x.ui.root = “xxx”;</p><p>var y = Object.create(RootObject);y.ui.root = “yyy”;</p><p>console.log(“x obj : “, x.ui.root);console.log(“y obj : “, y.ui.root);

Kode ini di atas akan menghasilkan output

x obj : yyyy obj : yyy

Output tersebut memperlihatkan dua instances yang kita buat menunjuk ke property root yang sama. Coba rubah property instance y dengan kode berikut

var x = Object.create(RootObject);x.ui.root = “xxx”;</p><p>var y = Object.create(RootObject);y.ui = { root: “yyy” };</p><p>console.log(“x obj : “, x.ui.root);console.log(“y obj : “, y.ui.root);

Kode di atas akan menghasilkan ouput berikut

x obj : xxxy obj : yyy

KMKLabs

Leave a comment