再讀ES6 proxy的方法 有讀到
get(target, propKey, receiver)
set(target, propKey, value, receiver)
想請問一下以上兩個方法裡面的參數 receiver 指的是甚麼?
簡單的例子:
let p = new Proxy({}, {
get: function(target, name, receiver) {
console.log('object been proxied', target);
console.log('accessed name', name);
console.log('parent:', receiver === p);
console.log('child(a):', !!a?receiver === a:null);
return 'ok\n====';
}
});
let A = function() {};
A.prototype = p;
let a = new A();
console.log(a.c);
console.log(p.c);
只是示範一下receiver是參考到哪個物件。如果直接使用proxy,就會指到proxy。但是如果是繼承了proxy的物件,那會指到該物件。
上例console.log(a.c);
結果是:
object been proxied {}
accessed name c
parent: false
child(a): true
ok
====
所以receiver是指到a。
而console.log(p.c);
結果是:
object been proxied {}
accessed name c
parent: true
child(a): false
ok
====
所以receiver是指到p。