So I'm using JSLint to try and detect errors. I turn some options off I don't like, but I don't see any way to enable being able to use the window
global variable. Well, there is the Yahoo Widget option, but that's overkill.
What's the deal with using 'window', why would JSLint say that is causing errors?
In HTML, the global scope is the window object. All global variables belong to the window object.
In a web browser, any code which the script doesn't specifically start up as a background task has a Window as its global object.
Correct way to declare global variable in JavaScript The proper way is to use window object. And use the syntax like this: var window. iAmGlobal = "some val" ; //Global variable declaration with window.
You should typically not use global variables unless absolutely necessary because global variables are only cleaned up when explicitly told to do so or your program ends. If you are running a multi-threaded application, multiple functions can write to the variable at the same time.
/*jslint browser: true*/
Was the correct solution to this. As of 2017-07-07, you have to set the global directive manually. From the JSLint documentation:
The /*global*/ directive is used to specify a set of globals (usually functions and objects containing functions) that are available to this file. This was commonly used in browsers to link source files together before ES6 modules appeared. Use of global variables is strongly discouraged, but unfortunately web browsers require their use. The /*global*/ directive can only be used when the Assume a browser option is selected.
So you will need to use:
/*jslint browser */ /*global window */
Just make a comment in your script like that:
/*global window */ ... your script goes here
This comment will tell JSLint that window
is defined somewhere else.
See: http://www.JSLint.com/lint.html,
JSLint also recognizes a
/* global */
comment that can indicate to JSLint that variables used in this file were defined in other files. The comment can contain a comma separated list of names. Each name can optionally be followed by a colon and either true or false, true indicated that the variable may be assigned to by this file, and false indicating that assignment is not allowed which is the default.
When you want window to be global by default without having to apply the comment to your script, you can add predef:["window"]
to the object literal parameter inside the JSLINT
function of your local jslint.js
file.
BTW, I'm using predef:["$","window"]
to have jQuery global as well.
Update:
This answer was correct back in 2009. As of now you should use the solution /*jslint browser: true*/
provided by Matt Clarkson.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With