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
var Node = function(k,v){ | |
if(!(k instanceof String)){ | |
throw new TypeError("Key value '" + k + "' must be a string"); | |
} | |
this.key = k; | |
this.value = v; | |
} |
That's when I noticed the following...
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
var first = new Node("key","val"); // (key instanceof String) is false | |
var second = new Node('key',"val"); // (key instanceof String) is false | |
var third = new Node(String("key"),"val"); // (key instanceof String) is false | |
var fourth = new Node(new String("key"),"val"); // (key instanceof String) is TRUE |
According to MDN (ctrl + f "Primitives and string objects") javascript handles string primitives differently from string objects. When creating a string with single or double quotes, or the global String object, javascript returns a primitive string. However, when creating a string with the new keyword, javascript returns a new string object. This makes sense when you read it, but if you're unaware or unfamiliar it could easily bite you.
Finally, the documentation does say that "JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings". The problem is that Javascript only does this for String object methods, but instanceof is not a string object method. Instead, since instanceof is a global relational operator, the string created by quotes remains a primitive string and fails the instanceof String test.
No comments:
Post a Comment