On this page
Proxy & Well-Known Symbols
Prev: Promise & Async | Up: builtins | Next: String, RegExp & Intl
Rel: Object & Reflect, Prototype Chain & new Instantiation Flow
Ref: MDN Web Docs — Proxy
Tags: #public #web #javascript #builtins #metaprogramming
Contents
Intercepting Operations with Proxy
Proxy wraps a target object and intercepts fundamental operations (get, set, has, deleteProperty, apply, construct), delegating default behavior via Reflect:
const reactive = (target, onChange) =>
new Proxy(target, {
set(obj, prop, value, receiver) {
const ok = Reflect.set(obj, prop, value, receiver);
onChange(prop, value);
return ok;
},
});
const state = reactive({ count: 0 }, (k, v) => console.log(`${String(k)} -> ${v}`));
state.count = 1;
Well-Known Symbols (JavaScript's Protocol Hooks)
Well-known symbols play the role of Python's dunder protocol methods:
Symbol.iterator/Symbol.asyncIterator: Enablesfor...of, spread..., andfor await...of.Symbol.toPrimitive: Customizes object-to-primitive conversion ("number","string","default").Symbol.toStringTag: CustomizesObject.prototype.toString.call(obj).
Linked from
- tuts/javascript/builtins
- tuts/javascript/builtins/object_and_reflect
- tuts/javascript/builtins/promise_and_async
- tuts/javascript/builtins/proxy_and_symbols
- tuts/javascript/builtins/string_regexp_and_intl
- tuts/javascript/tutorials/iterators_and_generators
- tuts/javascript/tutorials/prototype_chain_and_new_flow
Related notes
- tuts/javascript/builtins Linked here; links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/object_and_reflect Linked here; links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/promise_and_async Linked here; links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/string_regexp_and_intl Linked here; links to this page; shared tags: #builtins, #javascript, #web
- tuts/javascript/tutorials/prototype_chain_and_new_flow Linked here; links to this page; shared tags: #javascript, #web
- tuts/javascript/tutorials/iterators_and_generators links to this page; shared tags: #javascript, #web
- tuts/javascript/builtins/Array shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/Array/at shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/Array/filter shared tags: #builtins, #javascript, #web
- tuts/javascript/builtins/Array/find shared tags: #builtins, #javascript, #web