Created
April 21, 2013 18:26
-
-
Save beala/5430522 to your computer and use it in GitHub Desktop.
JS string weirdness
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
| /*Strings aren't objects.*/ | |
| typeof '' // 'string' | |
| '' instanceof Object // false | |
| /*But they have methods.*/ | |
| 'a'.concat(' string'); // 'a string' | |
| /*A string's methods are equal across receivers.*/ | |
| 'a'.concat === 'b'.concat // true | |
| /*String's methods (capital S) aren't.*/ | |
| (new String('a')).concat === (new String('b')).concat // false | |
| /*Even though a method isn't bound to its receiver.*/ | |
| var m = (new String('a')).concat | |
| m(' string') // TypeError: can't convert undefined to object (receiver is undefined) | |
| /*And a String's methods (capital S) return strings (lowercase S).*/ | |
| typeof new String('a') // 'Object' | |
| typeof (new String('a')).concat(' string') // 'string' | |
| /*loljs*/ |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ah wait a minute. This turns out to be true:
Which vaguely makes sense. Once
concatis assigned toaandb, neither has a receiver, so they're finally equal.