Created
August 11, 2016 21:58
-
-
Save dotproto/f4bb65ad97fc90bb4217434f39297feb to your computer and use it in GitHub Desktop.
Exploring Proxies & [Symbol.toPrimitive]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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