The usage summary _javascript skill of typeof in JS

Source: Internet
Author: User

The typeof in JavaScript is actually very complex, it can be used to do a lot of things, but at the same time there are a lot of weird performance. This article enumerates several usages of it, and also points out the existing problems and solutions.

https://developer.mozilla.org/en-us/docs/web/javascript/reference/operators/typeof?redirectlocale=en-us& Redirectslug=javascript%2freference%2foperators%2ftypeof

> 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 whether there is a value.
typeof will return "undefined" in two cases: when a variable is not declared, and when 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 detect whether a value is undefined:

> var value = undefined; > value = = undefined true
But this method throws an exception if it is used on an undeclared variable, because only typeof can detect undeclared variables without error:

> undeclaredvariable = = undefined referenceerror:undeclaredvariable = Not defined
Note: Uninitialized variables, no formal parameters that are passed in, no properties that do not exist, do not appear above the problem because they are always accessible and the values are always undefined:

> var declaredvariable; > declaredvariable = = undefined true > (function (x) {return x = = = undefined} ()) True > ({}). Foo = n undefined True
Therefore, if you want to detect the existence of a global variable that may not be declared, you can also use the IF (window.maybeundeclaredvariable) {}


Question: typeof is very complicated in accomplishing such a task.

Solution: This kind of operation is not very common, so some people feel that there is no need to find a better solution. But perhaps someone would suggest a special operator:

> defined undeclaredvariable false > var declaredvariable; > Defined declaredvariable False
Alternatively, someone might also need an operator that detects whether a variable is declared:

> declared undeclaredvariable false > var declaredvariable; > Declared declaredvariable True
Translator Note: In Perl, the defined operator above is equivalent to defined (), and the declared operator above is equivalent to exists (),

2. Judge a value not equal to undefined and not equal to NULL
Question: If you want to detect whether a value has been defined (the value is not undefined or null), then you encounter the TypeOf's most famous bizarre expression (considered a bug): typeof null Returns "Object":

> typeof null ' object '
Translator Note: This can only be said to be the original JavaScript implementation of the bug, and now the standard is such a specification. V8 has fixed and implemented typeof null = = "NULL", but the final proof is not OK. Http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null


Workaround: Do not use typeof to do this task, using the following function instead:

function isdefined (x) {return x!== null && x!== undefined;}
Another possibility is to introduce a "default value operator" that, in the case of myvalue undefined, returns the following expression defaultvalue:

MyValue?? DefaultValue
The expression above is equivalent to:

(myvalue!== undefined && myvalue!== null)? Myvalue:defaultvalue
Or:

MyValue?? = DefaultValue
This is actually a simplification of 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. You can allow the above expression to return the first property encountered with a value of undefined or null when traversing a layer of properties:

Obj.?? Foo.?? Bar
The expression above is equivalent to:

(obj = = Undefined | | | obj = = NULL)? Obj: (obj.foo = = Undefined | | | obj.foo = = NULL)? Obj.foo:obj.foo.bar

3. Distinguish between object values and original values
The following function is used to detect whether X is an object value:

function IsObject (x) {return (typeof x = = "function" | | (typeof x = = "Object" && x!== null)); }
Problem: The above detection is more complex because TypeOf regards functions and objects as different types, and typeof null returns "Object".

Workaround: The following methods are often used to detect object values:

function IsObject2 (x) {return x = = = = Object (x);}
Warning: You may think that you can use Instanceof object to detect this, but instanceof is using a prototype of an object to determine the instance relationship, so what about the object without a prototype:

> 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 practice, you may rarely encounter such an object, but it does exist and has its purpose.

Translator Note: Object.prototype is a default, no prototype object

>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 a raw value.

> typeof "abc" ' String ' > typeof undefined ' undefined '
Question: You must know the strange typeof of NULL.

> typeof null//Be careful! ' Object '
WORKAROUND: The following function can fix this problem (for this use case only).

function Getprimitivetypename (x) {var typeName = typeof x; switch (typeName) {case ' undefined ': Case ' boolean: Case ' num ber ": Case" string ": return typeName; Case "Object": if (x = = null) {return "null";} Default://Previous judgment did not pass throw new TypeError ("parameter is not an original value:" +x);}

A better solution: Implement a function Gettypename (), in addition to the type that can return the original value, you can return the internal [[Class]] property of the object value. Here's how to implement this function (translator: $.type in jquery is the implementation)

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

In principle, the instanceof function can also be tested for this requirement. At first glance, it looks more elegant. However, browsers have a quirk: each frame and window has its own global variables. So if you pass objects in one frame to another, Instanceof will not work properly because the two frameworks have different constructors. That's why the Array.isarray () method is ECMAScript5. If there is one that can cross the frame, It would be nice to check whether an object is an instance of a given constructor. The above Gettypename () is an available workaround, but there may be a more fundamental solution.

6. Overview
As mentioned below, this should be the most pressing need in current JavaScript to replace some of the functional features of TypeOf's current responsibilities:

IsDefined () (for example, object.isdefined ()): Can be used as a function or as an operator
IsObject ()
Gettypename ()
A mechanism that can cross a frame to detect whether an object is an instance of a specified constructor
It may not be necessary to have your own operator to check whether a variable has been declared as such.

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.