Harmony proxy, detect whether property was accessed or called

心已入冬 提交于 2020-07-22 21:40:24

问题


Is there a way using Proxy to detect if a property was executed, or was it just accessed?

'use strict';

require('harmony-reflect');

var Stub = {
    method: function (a) {
        console.log('q' + a + this.q);
    }
};

var ProxiedLibrary = {
    get: function (target, name, receiver) {
        if (name in target) {
            return target[name];
        }

        if (MAGIC_EXPRESSION) {
            return function() {
                return 'Return from nonexistent function!';
            };
        }

        return 'Property ' + name + ' is drunk and not available at the moment';
    }
};

var Library = new Proxy(Stub, ProxiedLibrary);

console.log(Library.nonexistent); //Everything is cool
console.log(Library.nonexistent()); //TypeError we don't want

I pretty much want to emulate php's __call and __get, preferably separaterly. try...catch block is not an option.

Thank you


回答1:


Is there a way using Proxy to detect if a property was executed, or was it just accessed?

No, as JavaScript does not distinguish between attributes and methods. It's all just properties that are accessed, and their value can be called if it's a function.

You would need to return a function (so that it can be called) but also mimics a string, maybe by tampering with the .valueOf()/.toString()/@@toPrimitive methods of that function object.




回答2:


I'm just a beginner with proxies, but as far as I know, the proxy cannot do what you need. It just gives you back the property you're looking for, it can't know how you're going to use it.



来源:https://stackoverflow.com/questions/27532794/harmony-proxy-detect-whether-property-was-accessed-or-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!