Multiple methods to determine whether JavaScript objects exist _javascript techniques

Source: Internet
Author: User
Tags hasownproperty
JavaScript language design is not rigorous, many places will be careless error.
For example, consider the following scenario.
Now, we want to determine whether a global object MyObj exists, and if not, declare it. The algorithms described in natural language are as follows:
Copy Code code as follows:

If (MyObj does not exist) {
Declaration of MyObj;
}

You might think it would be easy to write this piece of code. But in fact, it involves grammatical problems that are far more complicated than we think. Juriy Zaytsev points out that there are more than 50 ways to determine whether a JavaScript object exists or not. Only the details of the implementation of the JavaScript language are clear, and it is possible to distinguish between them.

The first form of writing
According to intuition, you might think you could write this:
Copy Code code as follows:

if (!myobj) {
myobj = {};
}

However, by running this code, the browser throws a referenceerror error directly, causing the run to break. Excuse me, where is the mistake?
Yes, if the IF statement to determine whether myobj is empty, this variable does not exist, it will be an error. Change to the following so that you can run it correctly.
Copy Code code as follows:

if (!myobj) {
var myobj = {};
}

Why did you add a var and then no more errors? Is this the case where the myobj already exists when the IF statement is judged?
To answer this question, you must know how the JavaScript interpreter works. The JavaScript language is "parse first, then run", when parsing has completed the variable declaration, so the above code is actually equivalent to:
Copy Code code as follows:

var myobj;
if (!myobj) {
var myobj = {};
}

Therefore, if the statement is made to judge, MyObj does exist, so there is no error. This is the "Code elevation" (hoisting) role of the Var command. The JavaScript interpreter, which only "promotes" the variables defined by the var command, does not work on variables that do not use the var command, directly assigned, and that is why VAR does not cause an error.

The second way
In addition to the Var command, you can have another rewrite and get the correct result:
Copy Code code as follows:

if (!window.myobj) {
myobj = {};
}

Window is the top-level object of JavaScript, and all global variables are its properties. Therefore, to determine whether the myobj is null equals to determine whether the Window object has a myobj attribute, so as to avoid referenceerror error because myobj is undefined. However, from the normative considerations of code, it is best to add Var to the second line:
Copy Code code as follows:

if (!window.myobj) {
var myobj = {};
}

or write this:
Copy Code code as follows:

if (!window.myobj) {
Window.myobj = {};
}

The Third Way of writing
The disadvantage of this type of writing is that in some running environments (such as V8, Rhino), Windows may not be the top-level object. So, consider changing it to:
Copy Code code as follows:

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

The Fourth way of writing
However, the above writing is less readable, and this point is variable and error prone, so it is further rewritten:
Copy Code code as follows:

var global = this;
if (!global.myobj) {
Global.myobj = {};
}

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

The fifth way of writing
You can also use the TypeOf operator to determine whether a myobj is defined.
Copy Code code as follows:

if (typeof myobj = = "undefined") {
var myobj = {};
}

This is the most widely used method to determine whether a JavaScript object exists.

The sixth way of writing
Because the value of myobj is directly equal to undefined in a defined but unassigned case, the above wording can be simplified:
Copy Code code as follows:

if (myobj = = undefined) {
var myobj = {};
}

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

The seventh way of writing
In the case of "exact comparison" (= = =), the above wording is still valid:
Copy Code code as follows:

if (myobj = = undefined) {
var myobj = {};
}

The eighth way of writing
According to JavaScript language design, undefined = = null, so compare myobj is equal to NULL, can also get the correct result:
Copy Code code as follows:

if (myobj = = null) {
var myobj = {};
}

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

The Nineth Way of writing
You can also use the in operator to determine whether MyObj is a property of a top-level object:
Copy Code code as follows:

if (! (' MyObj ' in Window ') {
Window.myobj = {};
}

The tenth way of writing
Finally, use the hasOwnProperty method to determine whether MyObj is a property of the top-level object:
Copy Code code as follows:

if (!this.hasownproperty (' myobj ')) {
This.myobj = {};
}

Summary
1. If you only judge whether the object exists, it is recommended to use the fifth way.
2. If in addition to the existence of the object, but also to determine whether the object has a null value, the recommended use of the first method.
3. All variables should be declared using the var command unless exceptional circumstances apply.
4. To cross platforms, it is recommended that you avoid using Windows to represent top-level objects.
5. In JavaScript languages, null and undefined are easily confusing. It is recommended that the exact comparison operator (= = =) be used in cases where both may be involved.
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.