var handler = {
get: function(target, name) {
if (name === 'prototype') {
return Object.prototype;
}
return 'Hello, ' + name;
},
apply: function(target, thisBinding, args) {
return args[0];
},
construct: function(target, args) {
return {value: args[1]};
}
};
var fproxy = new Proxy(function(x, y) {
return x + y;
}, handler);
fproxy(1, 2) // 1
new fproxy(1, 2) // {value: 2}
fproxy.prototype === Object.prototype // true
fproxy.foo === "Hello, foo" // true
https://es6.ruanyifeng.com/#docs/proxy
apply(target, object, args):拦截 Proxy 实例作为函数调用的操作,比如proxy(...args)、proxy.call(object, ...args)、proxy.apply(...)
所以执行
fproxy(1, 2)
会执行apply拦截里的代码,返回第一个参数1construct(target, args):拦截 Proxy 实例作为构造函数调用的操作,比如new proxy(...args)
所以执行
new fproxy(1, 2)
会执行construct里面的代码,返回{value: args[1]}
get(target, propKey, receiver):拦截对象属性的读取,比如proxy.foo和proxy['foo']
执行
fproxy.foo
会执行get里的代码