JS in typeof usage Summary [reprint]

Source: Internet
Author: User

The typeof in JavaScript is actually very complex, it can be used to do a lot of things, but also has a lot of weird performance. This article lists its many uses, but 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 if a variable exists and has a value.
typeof returns "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 if a value is undefined:

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

> undeclaredvariable = = = Undefined Referenceerror:undeclaredvariable is not defined
Note: Uninitialized variables that do not have parameters that are passed into the parameter, do not exist, and do not have the above problem because they are always accessible and the value is always undefined:

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


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

Workaround: Such operations are not very common, so some people feel that there is no need to find a better solution. But maybe someone will come up with a special operator:

> defined undeclaredvariable false > var declaredvariable; > Defined declaredvariable False
Or maybe someone needs an operator that detects whether a variable is declared:

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

2. Determine if a value is 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 have encountered TypeOf's most famous strange behavior (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 the norm. V8 has modified and implemented typeof null = = = "Null", but the final proof is not possible. Http://wiki.ecmascript.org/doku.php?id=harmony:typeof_null


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

function isDefined (x) {return x!== null && x!== undefined;}
Another possibility is to introduce a "default value operator", in which the following expression returns defaultvalue if MyValue is undefined:

MyValue?? DefaultValue
The above expression 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 property, such as bar, you may need help with 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 that is encountered with a value of undefined or null when traversing a layer of properties:

Obj.?? Foo.?? Bar
The above expression 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 if 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 functions and objects as different types, and typeof null returns "Object".

Workaround: The following methods are also frequently used to detect object values:

function IsObject2 (x) {return x = = = Object (x);}
Warning: You might think that this can be detected using Instanceof object, but instanceof is using a prototype of an object to determine the instance relationship, what about the object without the 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 object that has no 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 see the type of a primitive value.

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

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

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 also return the internal [[Class]] property of the object value. Here's how to implement this function (translator Note: $.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, instanceof function can also be used to detect such requirements. At first glance, it seems that the wording is more elegant. However, the browser has a quirk: each frame and window has its own global variables. So if you're uploading an object from one frame to another, Instanceof does not work properly because the two frameworks have different constructors. This is why there is a Array.isarray () method in ECMAScript5. If there is one that can cross the frame, The method used to check whether an object is an instance of a given constructor is fine. The above Gettypename () is an available workaround, but there may be a more fundamental solution.

6. Overview
As mentioned below, it should be the most urgently needed in JavaScript today, instead of some of the features of TypeOf's current responsibilities:

isDefined () (e.g. object.isdefined ()): Can be a function or an operator
IsObject ()
Gettypename ()
The ability to cross-frame a mechanism that detects 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 such a requirement.

Reprinted from Http://www.jb51.net/article/44372.htm

JS in typeof usage Summary [reprint]

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.