How to tell if a JavaScript object exists

Source: Internet
Author: User
Tags hasownproperty

The JavaScript language design is not rigorous enough, and many places will be wrong.

For example, consider the following scenario.

Now, we want to determine whether a global object MyObj exists and declare it if it doesn't exist. The algorithm described in natural language is as follows:

If (MyObj does not exist) {

Statement myobj;

}

You might think that it's easy to write this piece of code. But in fact, the grammatical problems it involves are far more complex than we thought. Juriy Zaytsev points out that there are more than 50 ways to determine whether a JavaScript object exists. Only the details of the implementation of the JavaScript language are very clear, it is possible to distinguish their differences.

The first form of a notation

According to intuition, you may feel that you can write:

if (!myobj) {

MYOBJ = {};

}

However, by running this code, the browser throws a Referenceerror error directly, resulting in a run-time outage. Excuse me, where is wrong?

Yes, if the statement determines whether the myobj is empty, this variable does not exist, so it will be an error. Change to the following so that it can be run correctly.

if (!myobj) {

var myObj = {};

}

Why did you add a var and don't get an error? In this case, if the statement is judged, myobj already exist?

To answer this question, you must know how the JavaScript interpreter works. The JavaScript language is "parse first, run later" and the declaration of variables is completed when parsing, so the above code is actually equivalent to:

var myObj;

if (!myobj) {

var myObj = {};

}

Therefore, if the statement is judged, myobj does exist, so it does not error. This is the "code boost" (hoisting) effect of the Var command. The JavaScript interpreter, which only "boosts" the variables defined by the var command, does not work with variables that do not use the var command, which is why the error is not added to Var.

The second type of notation

In addition to the Var command, you can have another rewrite and get the correct results:

if (!window.myobj) {

MYOBJ = {};

}

Window is the top-level object of JavaScript, and all global variables are its properties. So, judging whether myobj is empty is equivalent to judging if the Window object has a myobj attribute, so you can avoid referenceerror error because myobj is undefined. However, from the normative considerations of the code, it is better to add Var to the second line:

if (!window.myobj) {

var myObj = {};

}

Or write it like this:

if (!window.myobj) {

Window.myobj = {};

}

The third kind of wording

The downside of this notation is that in some operating environments (such as V8, Rhino), window is not necessarily the top-level object. So, consider changing it:

if (!this.myobj) {

This.myobj = {};

}

At the level of global variables, the This keyword always points to the top-level variable, so it can be independent of the different operating environments.

The fourth kind of notation

However, the above readability is poor, and this point is variable, error prone, so further rewrite:

var global = this;

if (!global.myobj) {

Global.myobj = {};

}

It is much clearer to use a custom variable global to represent the top-level object.

The fifth kind of notation

You can also use the TypeOf operator to determine whether a myobj is defined.

if (typeof myObj = = "undefined") {

var myObj = {};

}

This is currently the most widely used method of judging whether JavaScript objects exist.

The sixth kind of notation

Because the value of myobj is directly equal to undefined in the case of a defined, but not assigned value, the above notation can be simplified:

if (myObj = = undefined) {

var myObj = {};

}

Here are two places to note, first the second row of the Var keyword can not be less, otherwise there will be a referenceerror error, followed by undefined cannot add single or double quotation marks, because here is the undefined this data type, rather than "undefined" This string.

The seventh kind of notation

The above wording, in the case of "exact comparison" (= = =), still holds:

if (myObj = = = undefined) {

var myObj = {};

}

The eighth kind of notation

According to the language design of javascript, undefined = = NULL, so the comparison of myobj is equal to NULL, can also get the correct result:

if (MYOBJ = = null) {

var myObj = {};

}

However, although the results of the operation are correct, it is semantically wrong to be judged and should be avoided. Because null refers to an empty object that has been assigned a value of NULL, that is, the object actually has a value, and undefined refers to an object that does not exist or is not assigned a value. Therefore, only the comparison operator (= =) can be used here, and if the exact comparison operator (= = =) is used here, an error occurs.

The Nineth kind of notation

You can also use the in operator to determine whether MyObj is a property of the top-level object:

if (! (' MYOBJ ' in window) {

Window.myobj = {};

}

The tenth kind of notation

Finally, use the hasOwnProperty method to determine whether MyObj is a property of the top-level object:

if (!this.hasownproperty (' MYOBJ ')) {

This.myobj = {};

}

Summarize

1. It is recommended to use the fifth notation if the object is only determined to exist.

2. If you want to determine whether an object has a null value in addition to the object's existence, we recommend that you use the first notation.

3. Unless otherwise specified, all variables should be declared with the Var command.

4. For cross-platform, it is recommended that you avoid using window to represent top-level objects.

5. In the JavaScript language, null and undefined are prone to confusion. It is recommended to use the exact comparison operator (= = =) In cases where both may be involved.

Finish

How to tell if a JavaScript object exists

How to tell if a JavaScript object exists

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.