javascript - 在实例化对象时使用代理陷阱

时间:2017-07-29 20:14:17

标签: javascript

我想要一个可以实例化的javascript函数,并捕获每个被调用它的未定义方法(Proxy Trap)。

到目前为止我所拥有的是:

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();

但是,当我这样做时,{I} foo()不是一个功能。为什么?如何在实例化代理时使其工作?

1 个答案:

答案 0 :(得分:0)

该行为的解释是您的构造函数是代理的,而不是它构造的对象。因此,当您编写y + 11时,会调用代理构造函数,但构造函数会创建一个与new MyProxyFunction无关但与构造函数的Proxy属性无关的新对象。

有几种方法可以使它发挥作用。

1。在原型对象上应用代理

prototype

使用名称​​ MyProxyFunction 现在看起来有点奇怪,因为它不是代理的函数(构造函数)本身。

2。为每个实例创建一个代理

如果您希望每次使用它实例化对象时都有一个构造函数来创建一个新代理,那么不要将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);直接分配给new Proxy,而是将它作为一个普通的构造函数返回MyProxyFunction

您必须代理的对象是new Proxy

this

相关问题