Usage of JavaScript typeof

Source: Internet
Author: User
The typeof in JavaScript is actually very complicated. It can be used to do many things, but it also has a lot of weird performances. This article lists its usage and points out the existing problems and solutions. The premise for reading this article is that you should now know the original values and... syntaxHighlighter. all (); typeof in JavaScript is actually very complicated. It can be used to do many things, but it also has a lot of weird performances. This article lists its usage and points out the existing problems and solutions. The premise of reading this article is that you should now know the difference between the original value and the object value. Check whether a variable exists and whether there is a value typeof. In either case, "undefined" is returned: the value of the variable that is not declared is undefined. For example:> typeof undeclaredVariable = "undefined" true> var declaredVariable;> typeof declaredVariable 'undefined'> typeof undefined 'undefined' there are other ways to check whether a value is undefined:> var value = undefined;> value = undefinedtrue. However, if this method is used on an undeclared variable, an exception is thrown, because only typeof can normally detect undeclared variables without any error:> undeclaredVariable = undefinedReferenceError: un DeclaredVariable is not defined Note: Non-initialized variables, input parameters, and non-existent attributes will not cause the above problems, because they are always accessible, the value is always undefined:> var declaredVariable;> declaredVariable === undefinedtrue> (function (x) {return x === undefined} () true> ({}). foo = undefinedtrue Translator note: therefore, if you want to check whether a non-declared global variable exists, you can also use if (window. maybeUndeclaredVariable ){}. Problem: typeof is complicated when completing such a task. Solution: this operation is not very common, so some people think there is no need to find a better solution. However, some may come up with a special operator:> defined undeclaredVariablefalse> var declaredVariable;> defined declaredVariablefalse or, some may need an operator that checks whether a variable is declared:> declared undeclaredVariablefalse> var declaredVariable;> declared declaredVariabletrue note: in perl, the defined operator is equivalent to defined (), and the declared operator is equivalent to exists (). Judge whether a value is not undefined or null: If you want to check whether a value has been defined (the value is neither undefined nor null ), then you will encounter the most famous weird expression of typeof (considered a bug): typeof null returns "object":> typeof null 'object'. Note: this can only be said to be the bug of the original JavaScript implementation, and the standard is as standard as it is now. V8 corrected and implemented typeof null = "null", but eventually proved unfeasible. http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null . Note: typeof returns "object" when the operation is null, which is a bug in the JavaScript language. Unfortunately, this bug will never be fixed, because too many existing code already depends on this performance. But is null an object? Stackoverflow has a discussion about this issue: http://stackoverflow.com/questions/801032/null-object-in-javascript/7968470#7968470@justjavac ) Solution: Do not use typeof for this task. Use the following function instead: function isDefined (x) {return x! = Null & x! = Undefined;} another possibility is to introduce a "Default operator". When myValue is not defined, the following expression returns defaultValue: myValue ?? The expression above defaultValue is equivalent to: (myValue! = Undefined & myValue! = Null )? MyValue: defaultValue or: myValue ?? = DefaultValue is actually simplified in the following statement: myValue = myValue ?? DefaultValue when you access a nested attribute, such as bar, you may need the help of this operator: obj. foo. bar if obj or obj. foo is undefined. The above expression throws an exception. An operator .?? When the above expression traverses a layer-by-layer attribute, the first attribute that is undefined or null is returned: obj .?? Foo .?? The expression above bar is equivalent to: (obj = undefined | obj = null )? Obj: (obj. foo = undefined | obj. foo = null )? Obj. foo: obj. foo. bar distinguishes between object values and original values. The function below is used to check whether x is an object Value: function isObject (x) {return (typeof x = "function" | (typeof x = "object" & x! = Null);} problem: the above detection is complicated because typeof treats functions and objects as different types, and typeof null returns "object ". solution: the following method is often used to detect the Object Value: function isObject2 (x) {return x = Object (x);} warning: you may think that instanceof Object can be used for detection. However, instanceof uses the prototype of an Object to determine the relationship between instances. What if there is no prototype Object?> var obj = Object. create (null);> Object. getPrototypeOf (obj) nullobj is indeed an object, but it is not an example of any value:> typeof obj 'object'> obj instanceof Objectfalse in reality, you may rarely encounter such an object, but it does exist, and Its purpose. Note: Object. prototype is the only built-in Object without a prototype.> Object. getPrototypeOf (Object. prototype) null> typeof Object. prototype 'object'> object. prototype instanceof Object false what is the type of the original value? Typeof is the best way to view the type of an original value.> Typeof "abc" 'string'> typeof undefined 'undefined' problem: You must know the weird performance of typeof null.> Typeof null // be careful! 'Object' solution: the following function can fix this problem (only for this case ). Function getPrimitiveTypeName (x) {var typeName = typeof x; switch (typeName) {case "undefined": case "boolean": case "number": case "string": return typeName; case "object": if (x = null) {return "null";} default: // The previous judgment fails. throw new TypeError ("the parameter is not an original value: "+ x) ;}} better solution: implement a function getTypeName (), in addition to returning the type of the original value, you can also return the internal [Class] attribute of the object value. This article describes how to implement this function ($. type in jQuery is like this). Whether a value is a function typeof can be used to detect whether a value is a function.> Typeof function () {} 'function'> typeof Object. prototype. toString 'function' in principle, instanceof function can also be used to detect this requirement. At first glance, it seems that the writing style is more elegant. However, the browser has a quirk: Every framework and window has its own global variables. Therefore, if you upload objects in a framework to another framework, instanceof will not work normally, because the two frameworks have different constructors. This is why the Array. isArray () method exists in ECMAScript5. If there is a method that can be used across frameworks to check whether an object is an instance of a given constructor, it will be good. The above getTypeName () is an available work und, but there may be a more fundamental solution. The summary below should be the most urgent need of JavaScript, which can replace some functional features of typeof's current responsibilities: isDefined () (such as Object. isDefined (): it can be used as a function or an operator isObject () getTypeName () across frameworks, the mechanism of checking whether an object is a specified constructor instance checks whether a variable has been declared such a requirement, and may not have to have its own operators.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.