Introduction to the use of typeof in JavaScript _ basics

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.

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 has a value
typeof will return "undefined" in two cases:

1. Variables are not declared

2. The value of the variable is undefined

For example:

Copy Code code as follows:

> typeof undeclaredvariable = = "undefined"
True

> var declaredvariable;
> typeof declaredvariable
' Undefined '

> typeof undefined
' Undefined '

There are other ways to detect whether a value is undefined:

Copy Code code as follows:

> 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:

Copy Code code as follows:

> undeclaredvariable = = undefined
Referenceerror:undeclaredvariable is 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:

Copy Code code as follows:

> var declaredvariable;
> declaredvariable = = undefined
True

> (function (x) {return x = = = undefined} ())
True

> ({}). Foo = = 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:

Copy Code code as follows:

> Defined undeclaredvariable
False

> var declaredvariable;
> Defined declaredvariable
False

Alternatively, someone might also need an operator that detects whether a variable is declared:

Copy Code code as follows:

> 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 ().

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":

Copy Code code as follows:

> 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.

typeof returns "Object" when manipulating null, which is a bug in the JavaScript language itself. Unfortunately, this bug can never be fixed, because too many existing code already relies on this performance. But is null really the object? StackOverflow has a discussion on this issue: Http://stackoverflow.com/questions/801032/null-object-in-javascript/7968470#7968470@justjavac)

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

Copy Code code as follows:

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:

Copy Code code as follows:

MyValue?? DefaultValue

The expression above is equivalent to:

Copy Code code as follows:

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

Or:

Copy Code code as follows:

MyValue?? = DefaultValue

This is actually a simplification of the following statement:

Copy Code code as follows:

MyValue = myvalue?? DefaultValue

When you access a nested attribute, such as bar, you may need the help of this operator:

Copy Code code as follows:

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:

Copy Code code as follows:

Obj.?? Foo.?? Bar

The expression above is equivalent to:

Copy Code code as follows:

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

Differentiate between object values and original values

The following function is used to detect whether X is an object value:

Copy Code code as follows:

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:

Copy Code code as follows:

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:

Copy Code code as follows:

> var obj = object.create (null);
> object.getprototypeof (obj)
Null

Obj is indeed an object, but it is not an instance of any value:

Copy Code code as follows:

> 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 only a built-in, no prototype object.

Copy Code code as follows:

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

Copy Code code as follows:

> typeof "ABC"
' String '
> typeof undefined
' Undefined '

Question: You must know the strange typeof of NULL.

Copy Code code as follows:

> typeof null//Be careful!
' Object '

WORKAROUND: The following function can fix this problem (for this use case only).

Copy Code code as follows:

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://No previous judgment passed.
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 Note: $.type in JQuery is the implementation of this)

Whether a value is a function
typeof can be used to detect whether a value is a function.

Copy Code code as follows:

> typeof function () {}
' function '
> typeof Object.prototype.toString
' function '

In principle, the instanceof Function can also be tested for this requirement. At first glance, the wording looks more elegant. However, browsers have a quirk: each frame and window has its own global variables. Therefore, if you pass an object from one frame to another, instanceof will not work properly because the two frameworks have different constructors. That's why there's a Array.isarray () method in ECMAScript5. It would be nice to have a method that spans the framework 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.

Review
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 ()

• The mechanism that can cross frames 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.