代理方法不要调用



>我想让getter初始化对象的方法

    var phas = new Proxy({b:9,
            cont:0,
            statistic:function(){
                console.log(this.cont)
                this.cont++
                }
            }, {
                has: function (target, key) {
                    if (key == "a") return false;
                    return true;
                },

                apply: function () {
                    console.log('run call ')
                }
            }
    )
phas.run();

未捕获的类型错误:phas.run 不是一个函数

代理对象 https://www.xul.fr/javascript/proxy.php 手册

您似乎误解了代理的工作原理。

创建

代理时,将在该对象上创建代理。代理不会自动将自身扩展到对象的属性。

apply陷阱仅适用于函数,如果您代理了一个函数,然后调用它,它将按预期工作。

如果要动态创建方法,则需要执行如下操作:

var p = new Proxy({}, {
    get: function(target, prop) {
        // If the property exists, just return it
        if (prop in target) 
            return target[prop];
        // Otherwise, return a function
        return function() { console.log("Some method", prop); };
    }
});
p.run() //Logs: Some method run
typeof p.a == 'function' // true

最新更新