How to determine whether a Javascript Object exists in a simple example, javascript Object

Source: Internet
Author: User
Tags hasownproperty

How to determine whether a Javascript Object exists in a simple example, javascript Object

The Javascript language is not strictly designed, and errors may occur in many places when you are not careful.

For example, consider the following situations.

Now, we need to determine whether a global object myObj exists. If it does not exist, declare it. The algorithm described in natural language is as follows:

If (myObj does not exist) {declare myObj ;}

You may think it is easy to write this code. But in fact, the syntax involved is far more complex than we think. Juriy Zaytsev pointed out that there are more than 50 methods to determine whether a Javascript Object exists. Only when the implementation details of the Javascript language are very clear can the differences be clarified.

First Writing Method

Intuitively, you may think you can write like this:

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

However, when you run this code, the browser will directly throw a ReferenceError, resulting in an interrupted operation. Where is the error?

By the way, when the if statement determines whether myObj is null, this variable does not exist, so an error is reported. Change it to the following to run it correctly.

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

Why is no error reported after a var is added? In this case, does myObj already exist when the if statement is used for judgment?

To answer this question, you must know how the Javascript interpreter works. The Javascript language is "parse first, and then run". The variable declaration has been completed during parsing, so the above Code is actually equivalent:

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

Therefore, when the if statement is used to determine whether myObj exists, no error is reported. This is the role of the var command "code upgrade" (hoisting. The Javascript interpreter only "promotes" the variables defined by the var command. It does not work for variables that do not use the var command or assign values directly. This is why an error is reported if var is not added.

Method 2

In addition to the var command, you can also rewrite it to get the correct result:

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

Window is the top-level object of javascript, and all global variables are its attributes. Therefore, determining whether myobj is null is equivalent to determining whether the window object has the myobj attribute. This avoids ReferenceError because myObj is not defined. However, from the normative considerations of the Code, it is best to add var to the second line:

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

Or write it as follows:

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

Third Writing Method

The disadvantage of the above writing is that in some Running Environments (such as V8 and Rhino), Windows may not be top-level objects. Therefore, consider rewriting:

if (!this.myObj) {    this.myObj = { };  }

At the global variable level, this keyword always points to the top-level variable, so it can be independent from different runtime environments.

Fourth Writing Method

However, the above writing is less readable, And the point of this is variable, which is prone to errors, so further rewrite:

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

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

Fifth Writing Method

You can also use the typeof operator to determine whether myObj is defined.

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

This is the most widely used method to determine whether a javascript Object exists.

Method 6

Because the value of myObj is directly equal to undefined without being assigned a value, the preceding method can be simplified:

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

There are two points to note: first, the var keyword of the second line should not be less; otherwise, a ReferenceError error will occur. Secondly, undefined cannot be added with single quotation marks or double quotation marks, because undefined is the data type, instead of the "undefined" string.

Seventh Writing Method

The above statement is still true in the case of "exact comparison" (=:

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

Eighth Writing Method

According to the javascript language design, undefined = null. Therefore, you can get the correct result by comparing whether myObj is equal to null:

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

However, although the running results are correct, this method is incorrect in terms of semantics and should be avoided. Null indicates an empty object that has been assigned null values, that is, this object actually has a value, and undefined indicates an object that does not exist or has no value. Therefore, only the "comparison operator" (=) can be used here. If the "exact comparison operator" (=) is used here, an error occurs.

Ninth Writing Method

You can also use the in operator to determine whether myObj is an attribute of the top-level object:

if (!('myObj' in window)) {    window.myObj = { };  }

Method 10

Finally, use the hasOwnProperty method to determine whether myObj is an attribute of the top-level object:

if (!this.hasOwnProperty('myObj')) {    this.myObj = { };  }

Summary

1. If you only determine whether an object exists, the fifth method is recommended.

2. In addition to the existence of an object, we recommend that you use the first method to determine whether the object has a null value.

3. Unless otherwise specified, all variables should be declared using the var command.

4. We recommend that you avoid using window to represent top-level objects for cross-platform purposes.

5. In Javascript, null and undefined are prone to confusion. We recommend that you use the exact comparison operator (=) if both are involved ).

(End)

The simple example of how to determine whether a Javascript Object exists in the above section is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the help house.

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.