Symbols
Created
July 8, 2021 04:22
-
-
Save luisenriquecorona/ceaea74a4e2b9016f5a5c0d264ba670f to your computer and use it in GitHub Desktop.
Temperature
This file contains hidden or 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
function Temperature(degrees) { | |
this.degrees = degrees; | |
} | |
Temperature.prototype[Symbol.toPrimitive] = function(hint) { | |
switch (hint) { | |
case "string": | |
return this.degrees + "\u00b0"; // degrees symbol | |
case "number": | |
return this.degrees; | |
case "default": | |
return this.degrees + " degrees"; | |
} | |
}; | |
var freezing = new Temperature(32); | |
console.log(freezing + "!"); // "32 degrees!" | |
console.log(freezing / 2); // 16 | |
console.log(String(freezing)); // "32°" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment