Summary of the usage of the variable type function typeof in js, jstypeof

Source: Internet
Author: User

Summary of the usage of the variable type function typeof in js, jstypeof

1. role:

The typeof operator returns a string that represents the Data Type of the expression.
Possible strings include: "number", "string", "boolean", "object", "function", and "undefined ".

2. Description of common return values

Expression Return Value
Typeof undefined 'Undefined'
Typeof null 'Object'
Typeof true 'Boolean'
Typeof 123. 'Number'
Typeof "abc" 'String'
Typeof function (){} 'Function'
Typeof {} 'Object'
Typeof [] 'Object'
Typeof unknownVariable 'Undefined'

Note: The type return values are both strings and lowercase headers.

3. General applications:

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
Note:Therefore, if you want to check whether a declared global variable exists, you can also use if (window. maybeUndeclaredVariable ){}

Problem:Typeof is complex 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. replace it with the following method: But the variable x must be declared in advance; otherwise, an error is reported.

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

In fact, the following statement is simplified:

MyValue = myValue | defaultValue

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 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: // previous judgment failed throw new TypeError ("the parameter is not an original value:" + x );

}}

Better solution:To 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)

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.

In this js article, the usage Summary of the variable type function typeof is all the content that I have shared with you. I hope you can give us a reference and support for more.

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.