A summary of 10 methods for the existence of JS judgment object

Source: Internet
Author: User
Tags comparison hasownproperty

  This article is mainly about the existence of JS to determine whether the 10 methods are summarized, the need for friends can come to the reference, hope to help everyone else

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:     code is as follows: if (MyObj does not exist) {    declaration myobj;   }   You might find it easy to write this 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 method according to intuition, you may feel that you can write:     code is as follows: if (!myobj) {    myobj = {};   }   but, run This code, the browser will throw the Referenceerror error directly, causing the run to interrupt. 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.   Code is 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", parsing has completed the variable declaration, so the above code is actually equivalent to: The code is as follows: Var myobj;    if (!myobj) {    var myOb j = {};   }   Therefore, if statements are judged, 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 except VAR command, there can also be another rewrite, can also get the correct result:   Code as follows: if (!window.myobj) {    myobj = {};   }   window is JA The top-level object of the Vascript, 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 the code, it is best to add Var to the second line: The code is as follows:     if (!window.myobj) {        var myobj = {};       }    or write:        if (!window.myobj) {      &NB     Sp Window.myobj = {};       }   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. So, consider to rewrite:   code as follows: if (!this.myobj) {    this.myobj = {};   }   at the level of global variables, this keyword always points to the top Layer variables, so you can be independent of the different running environments.   Fourth Writing However, the above is less readable, and this point is variable and error-prone, so rewrite further: the code is as follows: var global = this;    if (!global.myobj) {    Global.myobj = {};   }   represents the top-level object with the custom variable global, which is much clearer. The   fifth can also use the TypeOf operator to determine whether a myobj is defined.   Code as follows: if (TYPEOF myobj = = "undefined") {    var myobj = {};   }   This is the most widely used method of determining whether a JavaScript object exists.   Sixth writing because the value of myobj is directly equal to undefined in a defined but unassigned case, the above wording can be simplified: The   code is 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 referenceerror errors, followed by undefined can not add single or double quotes, Because this compares to undefined this data type, not "undefined" this string. The seventh way of writing the above in the case of "exact comparison" (= = =) is still valid: The   code is as follows: if (myobj = = undefined) {    var myobj = {};  &   nbsp     The   eighth is based on JavaScript language design, undefined = null, so compare myobj is equal to NULL, can get the correct result: The code is as follows: if (myobj = null) {    var myobj = {};   }   However, although the results are correct, the semantics of 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 you can also use the in operator to determine whether MyObj is a property of the top-level object:     Copy code code as follows: if (! MyObj ' in Window ') {    window.myobj = {};   }   Tenth type of writing Finally,Use the hasOwnProperty method to determine whether MyObj is an attribute of the top-level object:   Code as follows: if (!this.hasownproperty (' myobj ')) {    this.myobj = {} ;   }   Summary 1. If you only judge whether an object exists, it is recommended to use the fifth way.   2. If you want to determine whether an object has a null value in addition to the object, it is recommended that you use the first method.   3. All variables should be declared with the Var command, except in exceptional cases.   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

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.