Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Javascript determine whether an object exists?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of Javascript how to judge the existence of the object, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this Javascript how to judge whether the object exists or not. Let's take a look.

The design of Javascript language is not rigorous enough, and many places will make mistakes if you are not careful.

For example, consider the following.

Now, we need to determine whether a global object myObj exists, and if not, declare it. The algorithms described in natural language are as follows:

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

You may find it easy to write this code. But in fact, the grammatical problems involved are far more complicated than we thought. Juriy Zaytsev points out that there are more than 50 ways to determine whether a Javascript object exists. Only when you have a clear understanding of the implementation details of the Javascript language is it possible to tell the difference between them.

The first way of writing

Intuitively, you might think you could write something like this:

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

However, when you run this code, the browser will directly throw a ReferenceError error, causing the run to be interrupted. Excuse me, what's wrong?

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

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

Why don't you make a mistake after adding a var? In this case, does the myObj already exist when the if statement makes a judgment?

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

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

Therefore, when the if statement makes a judgment, the myObj does already exist, so it does not report an error. This is the "hoisting" function of the var command. The Javascript interpreter, which only "promotes" variables defined by the var command, does not work on variables that do not use the var command and assign values directly, which is why an error will be reported without adding var.

The second way of writing

In addition to the var command, there is another rewrite that can also get the correct result:

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

Window is the top-level object of javascript, and all global variables are its properties. Therefore, judging whether the myobj is empty is equivalent to judging whether the window object has a myobj attribute, so that you can avoid ReferenceError errors because the myObj is not defined. However, from the standpoint of the code, * adds var to the second line:

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

Or write something like this:

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

The third way of writing

The drawback of the above approach is that in some runtime environments (such as V8, Rhino), window is not necessarily the top-level object. Therefore, consider rewriting it as:

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

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

The fourth way of writing

However, the readability of the above is poor, and the direction of the this is variable and error-prone, so it is further rewritten:

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

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

The fifth way of writing

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 or not.

The sixth way of writing

Because the value of myObj is directly equal to undefined when it is defined but not assigned, the above writing can be simplified:

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

There are two points to note here. First, the var keyword on the second line cannot be reduced, otherwise there will be a ReferenceError error. Secondly, undefined cannot add single or double quotation marks, because the data type undefined is compared here, not the string "undefined".

The seventh way of writing

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

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

The eighth way of writing

According to the language design of javascript, undefined = = null, so comparing whether myObj is equal to null can also get the correct result:

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

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

The ninth way of writing

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 = {};}

The tenth way of writing

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

If (! this.hasOwnProperty ('myObj')) {this.myObj = {};} this is the end of the article on "how to determine whether an object exists by Javascript". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to judge whether an object exists or not by Javascript". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report