簡體   English   中英

Javascript。 掛鈎 new MyClass()

[英]Javascript. Hooking into new MyClass()

我想在 new 運行之前或之后做一些事情。

function F() {

    this.init = function  () { alert(0) }

}

F.prototype.init = function () { alert(1) }

new F().init(); // Will not run mine, because on new F(), init is reassigned within the class.

我知道我可以創建自己的方法 function Create() { new F().init() }

但我想知道是否有辦法掛鈎新的函數調用?

我希望你明白我的意思。

new不是函數調用, F()是。 您可以執行以下操作,將F替換為您自己的委托。

function F() {
    this.init = function  () { alert(0) }
}

var oldF = F;
F = function() {
    oldF.apply(this, arguments);
    this.init = function() { alert(1); };
};

new F().init();

如果您希望實用程序函數執行此類操作:

function wrap(constructor, config) {
    return function() {
        constructor.apply(this, arguments);
        for (var key in config) {
            this[key] = config[key];
        }
    }
}

F = wrap(F, {init: function() { alert(1); }});

或使用提供此功能的許多框架/庫(ExtJS,jQuery,Prototype)之一。

以下討論

這可以讓您開始嘗試做的事情,但是我不能保證它在所有情況或實現下都有效(僅在V8上進行了測試)。 您可以將F存在的上下文作為附加參數傳遞,或確保對其進行應用/綁定/調用extend

function extend(constructor, config) {
    this[constructor.name] = function() {
        constructor.apply(this, arguments);
        for (var key in config) {
            this[key] = config[key];
        }
    }
}

extend(F, {init: function() { alert(1); }});

您可以使用Proxy 的 handler.construct()來掛鈎新的 Operator。 在這里,我更改了傳遞給 new WebSocket() 調用的參數:

let WebSocket = require('ws');
// let's hook the new WebSocket(...)
WebSocket = new Proxy(WebSocket, {
  construct: function(target, args, newTarget) {
    // https://github.com/websockets/ws/blob/8.4.0/lib/websocket.js#L51
    let [address, options] = args;  // the original constroctor actually has tree arguments, here we only use 2, to keep it simple

    const extraOptions = createWsOptions(address);

    options = {
      ...options,
      ...extraOptions
    };
    console.log(`options of new Websocket(): ${JSON.stringify(options, null, 2)}`);

    return new target(...[address, options]);
  }
});
ws = new WebSocket(aServer, {
  protocol: 'binary'
});

javascript中的構造方法與其他方法一樣,您真正要尋找的是javascript中的AOP

有關適用於JavaScript的一些好的AOP庫,請參見此問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM