Skip to content

Instantly share code, notes, and snippets.

@wentout
Last active February 13, 2021 11:00
Show Gist options
  • Save wentout/5577a8d5cef540581e56ae7ccab47e7a to your computer and use it in GitHub Desktop.
Save wentout/5577a8d5cef540581e56ae7ccab47e7a to your computer and use it in GitHub Desktop.
demo for fields through prototype chain proxy declaration
'use strict';
const globalProto = Object.getPrototypeOf(Object.getPrototypeOf(Object));
const theirs = new Proxy(globalProto, {
get (target, prop, receiver) {
debugger;
console.log('p_get', prop);
},
set (target, prop, value, receiver) {
console.log('p_set', prop, value);
// so we should add the value to the receiver
debugger;
return true;
}
});
try {
console.log(Object.setPrototypeOf(Object.prototype, theirs));
} catch (e) {
console.error(e);
}
const my = {
fdsa: 123
};
console.log(Object.getPrototypeOf(my))
console.log(Object.getPrototypeOf(my) === globalProto)
console.log(Object.getPrototypeOf(my))
console.log(Object.getPrototypeOf(my) === globalProto)
Reflect.setPrototypeOf(my, theirs);
my.asdf = 321;
console.log('aaa', my.asdf);
console.log('fdsa', my.fdsa);
const jet = function (obj) {
console.log('here');
Object.entries(obj).forEach(([key, value]) => {
console.log('key', key);
delete obj[key];
Reflect.defineProperty(obj, key, {
get () {
console.log('r_get', value);
return value;
},
set (_value) {
console.log('r_set init', value);
value = _value;
console.log('r_set completed', value);
return true;
}
})
});
};
jet(my);
my.fdsa = 54321;
my.fdsa = 12345;
console.log('my.fdsa', my.fdsa);
const third = {};
Reflect.setPrototypeOf(third, my);
third.fsda = 123;
console.log('third.fsda', my.fsda);
third.fdsa = '3rd → my : fdsa';
third.asdf = '3rd → my : asdf';
console.log('third.fsda', third.fdsa);
console.log('third.asdf', third.asdf);
console.log('third.hasOwn fdsa', Object.hasOwnProperty.call(third, 'fdsa'));
console.log('third.hasOwn asdf', Object.hasOwnProperty.call(third, 'asdf'));
console.log('my.hasOwn asdf', Object.hasOwnProperty.call(my, 'asdf'));
console.log('my.hasOwn fdsa', Object.hasOwnProperty.call(my, 'fdsa'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment