Last active
June 15, 2016 03:41
-
-
Save The-Quill/6d31d4aef337360fdd2855c89d8af546 to your computer and use it in GitHub Desktop.
Symbol.toPrimitive manipulation
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
var obj = { | |
[Symbol.toPrimitive](hint) { | |
if (hint == "number") { | |
return Object.keys(this).length; | |
} | |
if (hint == "string") { | |
return JSON.stringify(this); | |
} | |
}, | |
key: 'value', | |
2: 89, | |
cats: 'good', | |
dogs: 'good', | |
goats: 'bad' | |
}; | |
console.log(+obj); // 5 | |
console.log(String(obj)); // {"2":89,"key":"value","cats":"good","dogs":"good","goats":"bad"} |
What does obj + ""
do?
I wrote a constructor for it, but I can't seem to overload the wrapper Object
constructor:
function ObjQuill(obj){
var manipulatedObject = {
[Symbol.toPrimitive](hint) {
if (hint == "number") {
return Object.keys(this).length;
}
if (hint == "string") {
return JSON.stringify(this);
}
}
};
return Object.assign(manipulatedObject, obj);
}
var testObj = ObjQuill({cat: 'dog', dog: 'cat'});
console.log(+testObj ); // 2
console.log(String(testObj )); //"{"cat":"dog","dog":"cat"}"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wonder whether I could overload the
Object
constructor to apply that value to every incoming object