问题
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