How to determine whether a Javascript Object exists

Source: Internet
Author: User
Tags hasownproperty

JavascriptThe language design is not rigorous enough, and errors may occur when you are not careful in many places.

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:

 
 
  1. If (myObj does not exist ){
  2. Declare myObj;
  3. }

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:

 
 
  1. if (!myObj)   
  2. {  
  3. 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.

 
 
  1. if (!myObj)   
  2. {  
  3. 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:

 
 
  1. var myObj;  
  2. if (!myObj)   
  3. {  
  4. var myObj = { };  

Therefore, when the if statement is used to determine whether myObj exists, no error is reported. This is the "code upgrade" hoisting function of the var command. 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:

 
 
  1. if (!window.myObj)   
  2. {  
  3. 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:

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

Or write it as follows:

 
 
  1. if (!window.myObj)   
  2. {  
  3. 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:

 
 
  1. if (!this.myObj)   
  2. {  
  3. 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:

 
 
  1. var global = this;  
  2. if (!global.myObj)   
  3. {  
  4. 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.

 
 
  1. if (typeof myObj == "undefined")   
  2. {  
  3. 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:

 
 
  1. if (myObj == undefined)  
  2. {  
  3. 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 when "exact comparison" =:

 
 
  1. if (myObj === undefined)   
  2. {  
  3. 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:

 
 
  1. if (myObj == null)   
  2. {  
  3. 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 will occur.

Ninth Writing Method

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

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

Method 10

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

 
 
  1. if (!this.hasOwnProperty('myObj'))   
  2. {  
  3. 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 ).

Original article address:Http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.