簡體   English   中英

javascript-實例化對象時使用代理陷阱

[英]javascript - using Proxy trap when instantiating an object

我想要一個可以實例化的javascript函數,並捕獲正在調用它的每個未定義方法(代理陷阱)。

我到目前為止所擁有的是:

var MyProxyFunction = new Proxy(function () {
        console.log(">>>>>>>>>>>>>>>>>>>> constructor");
    }, {
    get: function(target, prop) {
        if (target[prop] === undefined) {
            return function()  {
                console.log('an otherwise undefined function!!');
            };
        }
        else {
            return target[prop];
        }
    }
});

現在,如果我調用MyProxyFunction.foo() ,它將被調用(我將看到“構造函數”啟動並從get函數獲取日志)。

但是我想做的是像下面這樣實例化該對象(並在構造函數中進行一些初始化):

var myObj = new MyProxyFunction();
myObj.foo();

但是當我這樣做時,我得到foo()不是一個函數。 為什么? 實例化代理時如何使它工作?

對此行為的解釋是,您的構造函數被代理了,但沒有構造它的對象。 因此,當您編寫new MyProxyFunction時,將new MyProxyFunction代理的構造函數,但是構造函數會創建一個新對象,該對象與Proxy無關,但與構造函數的prototype屬性無關。

有幾種方法可以使其工作。

1.將代理應用於原型對象

 function MyProxyFunction() { console.log(">>>>>>>>>>>>>>>>>>>> constructor"); }; MyProxyFunction.prototype = new Proxy(MyProxyFunction.prototype, { get: function(target, prop) { if (target[prop] === undefined) { return function() { console.log('an otherwise undefined function!!'); }; } else { return target[prop]; } } }); var myObj = new MyProxyFunction(); myObj.foo(); console.log('constructor:', myObj.constructor.name); console.log('Is instance of MyProxyFunction?: ', myObj instanceof MyProxyFunction); 

現在使用名稱MyProxyFunction看起來有點奇怪 ,因為不是代理的函數(構造函數)本身。

2.為每個實例創建一個代理

如果想讓構造函數每次用它實例化一個對象時都創建一個新的代理,則不MyProxyFunction new Proxy直接分配給MyProxyFunction ,而應使其成為返回一個new Proxy的普通構造函數。

然后,您必須代理的對象是this

 function MyProxyFunction() { console.log(">>>>>>>>>>>>>>>>>>>> constructor"); return new Proxy(this, { get: function(target, prop) { if (target[prop] === undefined) { return function() { console.log('an otherwise undefined function!!'); }; } else { return target[prop]; } } }); } var myObj = new MyProxyFunction(); myObj.foo(); console.log('constructor:', myObj.constructor.name); console.log('Is instance of MyProxyFunction?: ', myObj instanceof MyProxyFunction); 

暫無
暫無

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

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