JavaScript getPrototypeOf() 方法



在 JavaScript 中,Proxy 物件可以使用 handler.getPrototypeOf() 來攔截對 Object.getPrototypeOf() 的呼叫。它允許自定義原型檢索行為。當訪問物件的原型時,會呼叫 handler getPrototypeOf()。這使得可以動態控制原型訪問,從而實現虛擬化和封裝等功能。如果 handler 沒有定義 getPrototypeOf(),則執行預設的原型查詢。此方法對於包含繼承和物件組合等功能至關重要。

語法

以下是 JavaScript handler.getPrototypeOf() 方法的語法:

new Proxy(obj, {
   getPrototypeOf(target) {
      // …
   }
});

引數

  • target − 包含目標物件。

返回值

此方法返回一個物件,如果沒有返回物件則返回 null。

示例 1

讓我們來看下面的例子,我們將使用 handler.getPrototypeOf() 來檢索代理物件的原型。

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
   getPrototypeOf(target) {
      return Object.getPrototypeOf(target);
   }
};
const z = new Proxy(x, y);
document.write(y.getPrototypeOf(z) === Object.getPrototypeOf(z));
</script>
</body>
</html>

輸出

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

示例 2

考慮另一個場景,我們將阻止訪問目標物件的原型。

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
   getPrototypeOf: function(target) {
      return null;
   }
};
const z = new Proxy(x, y);
document.write(Object.getPrototypeOf(z));
</script>
</body>
</html>

輸出

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

示例 3

在下面的例子中,我們將使用 handler.getPrototypeOf() 來動態地將代理物件的原型調整為 Array.prototype。

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {};
const y = {
   getPrototypeOf(target) {
      return Array.prototype;
   }
};
const z = new Proxy(x, y);
document.write(y.getPrototypeOf(z) === Array.prototype);
</script>
</body>
</html>

當我們執行上述程式碼時,它將生成一個包含網頁上顯示的文字的輸出。

廣告