const sign = Symbol(); // remember, a Symbol is just a unique identifier
const zodiac = Symbol('dragon'); // the string 'dragon' is just a message to help us humans
typeof sign === 'symbol';
let obj = {};
obj[sign] = "Scorpio";
// attempting to get using dot notation doesn't work
obj.sign // undefined
// you MUST pass in the Symbol reference using bracket notation
obj[sign] // "Scorpio"
Object.keys(obj) // [] An empty array!
for (let sym of Object.getOwnPropertySymbols(obj)) console.log(sym) // 'Symbol()'
// app.js
const MY_METADATA = Symbol.for('metadata');
// this symbol is now stored in Symbol's global registry
// elsewhere in your runtime.js
if (obj[MY_METADATA]) doSomethingWithMyMetadata(obj);
else doSomethingElse();
// you can check out the message for symbols in your global registry
Symbol.keyFor(MY_METADATA) === 'metadata' // true
let obj = {a: 1};
Object.defineProperty(obj, 'b', {value: 2});
obj[Symbol('c')] = 3;
// the Reflect API knows about Symbols, of course
Reflect.ownKeys(obj); // ['a', 'b', Symbol(c)]
class Mirror {
constructor (size, showsYourDeepestDesires) {
this.size = size;
this.showsYourDeepestDesires = showsYourDeepestDesires;
}
}
// tap into construction meta-operation of classes/contructor functions
let erised = Reflect.construct(Mirror, ['large', true]);
erised.size; // 'large'
// hook into the target object's 'get' operation
let target = { foo: "Welcome, foo" }
let proxy = new Proxy(target, {
get (receiver, name) {
return name in receiver ? receiver[name] : throw new Error(`${name} is not a valid property!`)
}
})
proxy.foo === "Welcome, foo"
proxy.world === error!
// List of meta-operations (https://babeljs.io/docs/learn-es2015/#proxies)
// Many of these you totally know!
// The rest are just a google search away!
get: ..., // target.prop
set: ..., // target.prop = value
has: ..., // 'prop' in target
deleteProperty: ..., // delete target.prop
apply: ..., // target(...args)
construct: ..., // new target(...args)
getOwnPropertyDescriptor: ..., // Object.getOwnPropertyDescriptor(target, 'prop')
defineProperty: ..., // Object.defineProperty(target, 'prop', descriptor)
getPrototypeOf: ...,
// Object.getPrototypeOf(target), Reflect.getPrototypeOf(target),
// target.__proto__, object.isPrototypeOf(target), object instanceof target
setPrototypeOf: ..., // Object.setPrototypeOf(target), Reflect.setPrototypeOf(target)
enumerate: ..., // for (let i in target) {}
ownKeys: ..., // Object.keys(target)
preventExtensions: ..., // Object.preventExtensions(target)
isExtensible :... // Object.isExtensible(target)