Ale*_*lex 5 javascript proxy function node.js
__call
PHP中的魔法方法的等价物是什么?
我的印象是 Proxy 可以做到这一点,但它不能。
class MyClass{
constructor(){
return new Proxy(this, {
apply: function(target, thisArg, args){
console.log('call', thisArg, args);
return 'test';
},
get: function(target, prop){
console.log('get', prop, arguments);
}
});
}
}
var inst = new MyClass();
console.log(inst.foo(123));
Run Code Online (Sandbox Code Playgroud)
get
似乎有效,因为我看到“get foo”,但apply
没有。我得到的不是函数错误。
apply
实际上处理对对象本身的函数调用,即如果你这样做new Proxy(someFunction, { apply: ... })
,apply
会在被调用之前someFunction
被调用。
没有什么可以捕获对属性的调用,因为这是多余的——get
在返回属性时已经处理了。您可以简单地返回一个函数,然后在调用时产生一些调试输出。
class MyClass{
constructor(){
return new Proxy(this, {
get: function(target, prop) {
return function() {
console.log('function call', prop, arguments);
return 42;
};
}
});
}
}
var inst = new MyClass();
console.log(inst.foo(123));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3159 次 |
最近记录: |