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:

[code lang=text]var RootObject = {ui : {root : { }}}

var x = Object.create(RootObject);x.ui.root = “xxx”;console.log(“x obj : “, x.ui.root);[/code]

Kode di atas akan menghasilkan output

x obj : xxx

Kita coba buat object baru dengan kode berikut

[code lang=text]var x = Object.create(RootObject);x.ui.root = “xxx”;

var y = Object.create(RootObject);y.ui.root = “yyy”;

console.log(“x obj : “, x.ui.root);console.log(“y obj : “, y.ui.root);[/code]

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

[code lang=text]var x = Object.create(RootObject);x.ui.root = “xxx”;

var y = Object.create(RootObject);y.ui = { root: “yyy” };

console.log(“x obj : “, x.ui.root);console.log(“y obj : “, y.ui.root);[/code]

Kode di atas akan menghasilkan ouput berikut

x obj : xxxy obj : yyy

KMKLabs