Does Javascript / jQuery have system vars?

2019-06-06 20:35发布

问题:

I noticed strange issue.

Look at this jQuery:

$(function(){
    status = 1;
    status1 = 2;

    $('body').append(status+' - '+status1);
});

Fiddle

As you can see output is:

- 2

So status is system var for JavaScript or jQuery?

And is there any other vars like this?

回答1:

JavaScript has global variables and in browsers, global variables are properties of the global object which is window.

Now, window itself has a couple of predefined properties and some of them are read-only, like window.status [MDN] (this can also differ from browser to browser!). Creating a global variable with such a name will therefore fail (the variable already exists, but you cannot assign a new value to it).

You can find a list of predefined properties in the MDN documentation.


This one of the reasons why you should avoid global variables. If you use local variables (by declaring variables with var and if necessary, put all your code in a function), you don't have this problem:

(function() {
    var status = 'foo';
    // ....
}());


回答2:

The global object window does have a property called status used for setting the text in the status bar at the bottom of the browser.

By not using the var keyword you are overwriting this property as you refer to window.status. Apparently Firefox won't let you change this though as long as the user hasn't set the dom.disable_window_status_change preference to false.

See this link for documentation and this one for a list of all "global" properties.

Also there are some words in JS that are considered reserved, so you should avoid using these, even in local scopes.