Summary of typeof usage in js _ javascript skills

Source: Internet
Author: User
This article mainly summarizes the usage of typeof in js. If you need a friend, you can refer to it and hope to help you with the complexity of typeof in JavaScript, 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.

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof? Redirectlocale = en-US & redirectslug = JavaScript % 2 FReference % 2 FOperators % 2 Ftypeof

> Typeof undefined
'Undefined'
> Typeof null // well-known bug
'Object'
> Typeof true
'Boolean'
> Typeof 123
'Number'
> Typeof "abc"
'String'
> Typeof function (){}
'Function'
> Typeof {}
'Object'
> Typeof []
'Object'
> Typeof unknownVariable
'Undefined'

1. check whether a variable exists and has a value.
Typeof returns "undefined" in two cases: when a variable is not declared and the value of a variable 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 = undefined true
However, if this method is used on an undeclared variable, an exception will be thrown, because only typeof can normally detect undeclared variables without returning an error:

> UndeclaredVariable === undefined ReferenceError: undeclaredVariable is not defined
Note: Non-initialized variables, input parameter parameters, and non-existent attributes will not cause the above problems, because they are always accessible and the values are always undefined:

> Var declaredVariable;> declaredVariable === undefined true> (function (x) {return x === undefined} () true> ({}). foo = undefined true
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 such a task is completed.

Solution: this operation is not very common, so some people think there is no need to find a better solution. However, some people may propose a special operator:

> Defined undeclaredVariable false> var declaredVariable;> defined declaredVariable false
Alternatively, someone may need an operator that checks whether a variable is declared:

> Declared undeclaredVariable false> var declaredVariable;> declared declaredVariable true
Note: In perl, the defined operator is equivalent to defined (), and the declared operator is equivalent to exists (),

2. judge whether a value is not equal to undefined or null.
Problem: If you want to check whether a value has been defined (neither undefined nor null), you will encounter the most famous weird expression of typeof (considered a bug): typeof null returned "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


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 undefined, the following expression returns defaultValue:

MyValue ?? DefaultValue
The above expression is equivalent:

(MyValue! = Undefined & myValue! = Null )? MyValue: defaultValue
Or:

MyValue ?? = DefaultValue
In fact, the following statement is simplified:

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 will throw 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 .?? Bar
The above expression is equivalent:

(Obj = undefined | obj = null )? Obj: (obj. foo = undefined | obj. foo = null )? Obj. foo: obj. foo. bar

3. differentiate object values from original values
The following function is used to check whether x is an object value:

Function isObject (x) {return (typeof x = "function" | (typeof x = "object" & amp; x! = Null ));}
Problem: The preceding 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 object values:

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) null
Obj is indeed an object, but it is not an instance of any value:

> Typeof obj 'object'> obj instanceof object false
In reality, you may rarely encounter such an object, but it does exist and has its purpose.

Note: Object. prototype is a default Object without a prototype.

> Object. getPrototypeOf (Object. prototype) null> typeof Object. prototype 'object'> object. prototype instanceof Object false

4. 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 solve 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 (). Besides 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)

5. Whether a value is a function
Typeof can be used to check whether a value is a function.> typeof function () {} 'function'> typeof Object. prototype. toString 'function'

In principle, instanceof Function can also be used to detect such requirements. 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 ECMAScript5 contains an Array. the reason for the isArray () method. 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.

6. Summary
As mentioned below, it should be the most urgent need in JavaScript, which can replace some functional features of typeof's current responsibilities:

IsDefined () (such as Object. isDefined (): can be used as a function or an operator
IsObject ()
GetTypeName ()
It can detect whether an object is an instance of a specified constructor across frameworks.
Check whether a variable has been declared with such a requirement. It may not be necessary to have its own operators.

Related Article

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.