There is one caveat: You still need to use typeof for unknown variables. GetTypeName(new Boolean(true)) // "Boolean" GetTypeName(new String("abc")) // "String" GetTypeName(new ReferenceError()) // "ReferenceError" The article “ Fixing the JavaScript typeof operator” (by Angus Croll) makes use of this fact to define a toType() function that uses a regular expression to extract the value of ] from between the square brackets. While toString() is overridden in subclasses of Object, you can apply () generically to get the original functionality back: Object, the second word in the square brackets, comes from ]. There is no way to access this value directly from JavaScript, however () uses it: The ECMAScript 5 specification defines the internal ] property as follows (8.6.2 “Object Internal Properties and Methods”, Table 8):Ī String value indicating a specification defined classification of objects. One could also argue that for an object, typeof should return the name of the object’s type. The typeof in JavaScript will return string as the result of an empty string, a string of characters, a string of multiple words, numbers in quotes, use of typeof, and conversions with the String function. instanceof always returns false for primitive values. For this example, we will pass string operands. Use instanceof to determine whether an object is an instance of a given type. This will probably be fixed in ECMAScript.next and the return value will then be "null". Code : if(typeof exports object & typeof module. Typeof null returning "object" is clearly a bug. Hey I saw this piece of code in any javascript code of a website or libraries like jQuery. Use typeof to find out whether a given value is an object or a primitive and, in the latter case, what type of primitive it is. This blog post explains how to fix it and how to extend its use to objects. The typeof operator in JavaScript is partially broken.
0 Comments
Leave a Reply. |