JavaScript Handler construct() 方法



JavaScript 中的handler.construct() 方法與 Proxy 物件一起使用,它允許您為物件上的基本操作定義自定義行為。當您使用 Proxy 物件作為建構函式時,將呼叫此方法。藉助 Proxy 物件,您可以封裝另一個物件並使用它來攔截和修改其操作。

Handler.construct() 允許您修改代理物件例項的構建方式的所有內容,包括新增更多初始化邏輯、新增日誌記錄,甚至完全更改行為。

語法

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

const p = new Proxy(target, {
   construct: function(target, argumentsList, newTarget) {}
});

引數

  • target - 包含目標物件。
  • argumentsList - 建構函式的 this 引數。
  • newTarget - 包含最初呼叫的建構函式。

返回值

此方法返回一個物件。

示例 1

讓我們看下面的例子,我們將記錄在建立實際例項之前建立類的新例項。

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const examp = {
   construct(x, y) {
      document.write(`Creating new instance of ${x.name}`);
      return new x(...y);
   }
};
class tp {
   constructor(name) {
      this.name = name;
   }
}
const a = new Proxy(tp, examp);
const b = new a('Welcome');
</script>
</body>
</html>

輸出

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

示例 2

考慮另一種情況,我們將檢查是否只建立了一個類的例項,並在後續呼叫時返回相同的例項。

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const examp = {
   construct(x, y) {
      if (!x.instance) {
         x.instance = new x(...y);
      }
      return x.instance;
   }
};
class tp {}
const a = new Proxy(tp, examp);
const x1 = new a();
const x2 = new a();
document.write(x1 === x2);
</script>
</body>
</html>

輸出

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

示例 3

在下面的示例中,我們將向建構函式新增額外的邏輯。

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
function bike(x, y) {
   this.x = x;
   this.y = y;
   this.fullName = function() {
      return this.x + ' ' + this.y;
   };
}
const examp = {
   construct(a, b) {
      const z = new a(...b);
      z.year = new Date().getFullYear();
      return z;
   }
};
const c = new Proxy(bike, examp);
const d = new c("Vespa", "Bullet");
document.write(d.fullName() + " < br > "); 
document.write(d.year);
</script>
</body>
</html>

當我們執行上述指令碼時,將彈出輸出視窗,在網頁上顯示文字。

廣告