如何使用 object() 建構函式來建立 JavaScript 物件?


建構函式是一個建立並初始化物件的函式。JavaScript 提供了一個稱為 Object() 的特殊建構函式來構建物件。Object() 建構函式的返回值被分配給一個變數。

該變數包含對新物件的引用。分配給物件的屬性不是變數,並且不用 var 關鍵字定義。

示例

你可以嘗試執行以下程式碼來學習如何使用 object() 建構函式來處理 JavaScript 物件 −

演示

<html>
   <head>
      <title>User-defined objects</title>
      <script>
         var book = new Object(); // Create the object
         book.subject = "Perl"; // Assign properties to the object
         book.author = "Tutorialspoint";
      </script>
   </head>
   <body>
      <script type="text/javascript">
         document.write("Book name is : " + book.subject + "<br>");
         document.write("Book author is : " + book.author + "<br>");
      </script>
   </body>
</html>

輸出

Book name is : Perl
Book author is : Tutorialspoint

更新於: 2020-6-16

312 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.