Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - What are some of the problems of "Implied Global variables"?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...