Skip to content

Instantly share code, notes, and snippets.

@dotproto
Created August 11, 2016 21:58
Show Gist options
  • Save dotproto/f4bb65ad97fc90bb4217434f39297feb to your computer and use it in GitHub Desktop.
Save dotproto/f4bb65ad97fc90bb4217434f39297feb to your computer and use it in GitHub Desktop.
Exploring Proxies & [Symbol.toPrimitive]
// http://www.ecma-international.org/ecma-262/6.0/#sec-symbol.toprimitive
let base = {
[Symbol.toPrimitive] : hint => {
console.log(`toPrimitive hint: ${hint}`)
return 1;
},
valueOf: () => 2,
toString: () => '3',
};
let myProxy = new Proxy(base, {
get : function (target, name) {
if (!(name in target)) {
return 'not found'
}
return target[name]
}
});
console.log('--- number')
console.log(+myProxy)
console.log('--- string')
console.log(`${myProxy}`)
console.log('--- default')
console.log(myProxy + "")
console.log('--- N/A - doesn\'t call toPrimitive')
console.log(myProxy.toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment