Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

JavaScript: The Good Parts defines these kinds of declarations as bad:

foo = value;

The book says "JavaScript’s policy of making forgotten variables global creates bugs that can be very difficult to find."

What are some of the problems of these implied global variables other than the usual dangers of typical global variables?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

As discussed in the comments on this answer, setting certain values can have unexpected consequences.

In Javascript, this is more likely because setting a global variable actually means setting a property of the window object. For instance:

function foo (input) {
    top = 45;
    return top * input;
}
foo(5);

This returns NaN because you can't set window.top and multiplying a window object doesn't work. Changing it to var top = 45 works.

Other values that you can't change include document. Furthermore, there are other global variables that, when set, do exciting things. For instance, setting window.status updates the browser's status bar value and window.location goes to a new location.

Finally, if you update some values, you may lose some functionality. If, for instance, you set window.frames to a string, for instance, you can't use window.frames[0] to access a frame.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...