如何使用自身原型訪問 JavaScript 物件?


使用稱為“Object.create()”的 JavaScript 方法,我們可以透過建立自身原型來訪問現有物件。使用此方法,我們可以將現有屬性的屬性繼承到新建立的原型。讓我們簡要討論一下它。

語法

Object.create(existing obj);

此方法採用現有物件並建立其自身原型,以便將屬性從現有物件繼承到新建立的原型

示例

在以下示例中,首先,建立一個名為“person”的物件,然後使用 “Object.create”建立其自身原型並將其分配給變數 “newper”。稍後,使用原型,現有物件中的物件已更改,並在輸出中顯示了新屬性。

 即時演示

<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

更新於: 2019 年 8 月 26 日

337 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告