เราสามารถเข้าถึง Existing Object ได้โดยสร้าง Prototype ของตัวมันเองด้วยเมธอด JavaScript ชื่อ "Object.create()" ใช้เมธอดนี้สืบทอด Properties จาก Existing Object ไปยัง Prototype ที่สร้างใหม่ มาดูรายละเอียดกัน
Syntax
Object.create(existing obj);
เมธอดนี้รับ Existing Object และสร้าง Prototype ของตัวเอง เพื่อให้ Properties ถูก Inherited จาก Existing Object ไปยัง Newly Created Prototype
ตัวอย่าง
ในตัวอย่างนี้ สร้าง Object ชื่อ "person" แล้วใช้ "Object.create" สร้าง Prototype ของตัวเอง Assign ให้ Variable "newper" ต่อมาใช้ Prototype เปลี่ยน Properties ของ Existing Object และแสดง Properties ใหม่ตาม Output
<html> <body> <script> var person = { name: "Karthee", profession : "Actor", industry: "Tamil" }; document.write(person.name); document.write("</br>"); document.write(person.profession); document.write("</br>"); document.write(person.industry); document.write("</br>"); document.write("Using a prototype the properties of the existing object have been changed to the following"); document.write("</br>"); var newper = Object.create(person); /// creating prototype newper.name = "sachin"; newper.profession = "crickter"; newper.industry = "sports"; document.write(newper.name); document.write("</br>"); document.write(newper.profession); document.write("</br>"); document.write(newper.industry); </script> </body> </html>
ผลลัพธ์
Karthee Actor Tamil Using a prototype the properties of the existing object have been changed to the following sachin crickter sports