10 ways to determine whether a JavaScript object exists __java

Source: Internet
Author: User
Tags hasownproperty
There are a number of ways to determine whether a JavaScript object exists, but it is possible to distinguish between them only if the details of the implementation of the JavaScript language are clear. Let's take a look at 10 ways to determine whether a JavaScript object exists.
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 algorithm described in natural language is as follows:
If (MyObj does not exist) {declares myobj;}
You might think it's easy to write this code. But in fact, it involves a much more complicated grammatical problem 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 enough to distinguish between them.
The first form of writing
According to intuition, you might think you could write this:
if (. MyObj)
{myobj = {};}
However, by running this code, the browser throws a referenceerror error directly, causing the run to break. Excuse me, what's wrong?
By the way, 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 correctly.
if (. MyObj)
{var myobj = {};}
Why add a var after, no error. Is this the case where the myobj already exists when the IF statement is judged?
To answer this question, you know how the JavaScript interpreter works. The JavaScript language is "parse first, then run", and when parsing, the variable declaration has been completed, and the code above is actually equivalent to:
var myobj; if (. MyObj)
{var myobj = {};}
Therefore, if the statement is to make judgments, myobj does exist, there is no error. This is the "Code elevation" (hoisting) effect 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:
if (. Window.myobj)
{myobj = {};}
Window is the top-level object of JavaScript, and all global variables are its properties. To determine whether the myobj is empty is equivalent to determining whether the Window object has a myobj attribute. This avoids the referenceerror error myobj undefined. However, from the normative considerations of code, it is best to add Var to the second line:
if (. Window.myobj)
{var myobj = {};}
or write this:
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), window is not necessarily a top-level object. Consider changing it to:
if (. This.myobj)
{this.myobj = {};}

At the level of global variables, the This keyword always points to the top-level variable and can be isolated from the different running environments


The fourth way of writing
However, the above writing is less readable, this point is variable, error prone, and further rewritten:
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.
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
In a defined, but unassigned case, the value of the myobj is directly equal to the undefined, which can be simplified by:
if (myobj = = undefined)
{var myobj = {};}
Here are two places to note that 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, where the comparison is 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:
if (myobj = = undefined)
{var myobj = {};}
The eighth way of writing
Based on the language design of javascript, undefined = = NULL to compare whether myobj equals null, can also get the correct result:
if (myobj = null)
{var myobj = {};}
However, although the results of the operation are correct, from a semantic perspective, this method of judgment is wrong and should be avoided. Null refers to an empty object that has been assigned null, that is, the object is actually a value, and undefined refers to an object that does not exist or is not assigned. Therefore, you can only use the comparison operator (= =) 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:
if (. (' myobj ' in window)
{window.myobj = {};}
The tenth way, using the hasOwnProperty method, is to determine whether MyObj is a property of the top-level object:
if (. This.hasownproperty (' myobj '))
{this.myobj = {};}
Summary of the 1. If you only judge whether an 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 prone to confusion. 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.