javascript - 代理申请方法不调用

标签 javascript

我想要有 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();

Uncaught TypeError: phas.run is not a function

代理对象手册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

关于javascript - 代理申请方法不调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42024588/

相关文章:

javascript - 我应该如何解析 Highcharts 的日期时间?

javascript - 为循环分配名称

Javascript++ 与 +=1

javascript - 禁用滚动时,传单 map 标记拖动在移动设备上无法正常工作

javascript - Chunk.entrypoints : Use Chunks. groupsIterable 并通过 instanceof Entrypoint 过滤

javascript - 在 Nodejs 中访问请求参数

javascript - 是否存在一种方法来检查可观察对象是热的还是冷的?

javascript - 缓冲 rx.js observable 的多个订阅者

javascript - 关于第一个 :child and last:child in CSS 的问题

javascript - 一次对多列进行排序