JavaScript - Symbol.toStringTag 屬性



Symbol.toStringTag 屬性是一個內建的符號值,用於自定義物件的預設字串描述。當物件轉換為字串時(通常透過 Object.prototype.toString() 方法),它允許開發者為物件的型別提供自定義的字串表示。

當你對一個物件呼叫 toString() 方法時,JavaScript 內部會呼叫 Object.prototype.toString(),它返回一個包含物件型別的字串。預設情況下,此字串表示為 [object Object]。但是,你可以使用 Symbol.toStringTag 屬性更改此表示,以提供有關物件型別的更多詳細資訊。

語法

以下是 JavaScript Symbol.toStringTag 屬性的語法:

Symbol.toStringTag

引數

此屬性不接受任何引數。

返回值

此屬性返回一個字串物件。

示例

示例 1

讓我們來看下面的例子,我們將自定義使用者定義物件上的 toStringTag 表示。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = {
            name: 'Tessa',
            age: 24,
            [Symbol.toStringTag]: 'PersonDetails'
         };
         document.write(Object.prototype.toString.call(x));
      </script>
   </body>
</html>

如果我們執行上面的程式,它將在網頁上顯示文字。

示例 2

考慮另一種情況,我們將為自定義類定製 toStringTag 表示。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class Bike {
            constructor(x) {
               this.x = x;
            }
            get[Symbol.toStringTag]() {
               return 'Bike';
            }
         }
         const a = new Bike('R15');
         document.write(Object.prototype.toString.call(a));
      </script>
   </body>
</html>

執行上述指令碼後,它將在網頁上顯示文字。

示例 3

在下面的例子中,我們將 Symbol.toStringTag 與派生類一起使用。

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         class x extends Array {
            get[Symbol.toStringTag]() {
               return 'TP';
            }
         }
         const y = new x(11, 22, 33);
         document.write(Object.prototype.toString.call(y));
      </script>
   </body>
</html>

當我們執行指令碼時,它將在網頁上顯示文字。

廣告