简体   繁体   中英

JavaScript jQuery Variables i should avoid using that conflicts with Global variables

What are JavaScript/jQuery variable names i should avoid creating that could conflict with already existing Global variables. Yesterday i discovered that i cannot use the variable default . It must be a global variable.

default is not a global variable: it is a reserved word (it's used in switch statements).

You can find a list of reserved keywords on the MDC website .

Note also that there are various other names that you should be careful with. For instance, a variable named location could conflict with the window.location object unless you're careful. For this reason (among others), you should avoid global variables.

Other such variables are:

  • window.top
  • window.parent
  • window.document
  • window.self
  • and quite a few more.

default is one of the JavaScript reserved words (which is also the list of variables to avoid using). jQuery wise it is $ although you can use jQuery in no conflict mode .

default is a JavaScript keyword:

switch(foo)
{
    case a:
        break;
    default:
        break;
}

As for jQuery reserved words, check out this link (scroll down to the "Reserved Words" section)

These are JavaScript's reserved words:

  • abstract
  • boolean, break, byte
  • case, catch, char, class, const, continue
  • debugger, default, delete, do, double
  • else, enum, export, extends
  • false, final, finally, float, for, function
  • goto
  • if, implements, import, in, instanceof, int, interface
  • long
  • native, new, null
  • package, private, protected, public
  • return
  • short, static, super, switch, synchronized
  • this, throw, throws, transient, true, try, typeof
  • var, volatile, void
  • while, with

You should avoid naming you variables the same as that list.

I hope this helps.
Hristo

default is not a global variable, it's a reserved word in JavaScript.

If you are going to use global variables, you should namespace them .

Take a look at:

http://jqfundamentals.com/book/index.html

There's a special content of reserved words.

when building jQuery plugins, be aware that $.fn.init = function() could lead to problems and you should rather use another name for your function. http://www.sarahleeashraf.com/explaining-jquery-part-2-init-function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM