Skip to content

Instantly share code, notes, and snippets.

@The-Quill
Last active June 15, 2016 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save The-Quill/6d31d4aef337360fdd2855c89d8af546 to your computer and use it in GitHub Desktop.
Save The-Quill/6d31d4aef337360fdd2855c89d8af546 to your computer and use it in GitHub Desktop.
Symbol.toPrimitive manipulation
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"}
@The-Quill
Copy link
Author

I wonder whether I could overload the Objectconstructor to apply that value to every incoming object

@ConorOBrien-Foxx
Copy link

What does obj + "" do?

@The-Quill
Copy link
Author

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