开发者

JavaScript and leaking global variables

In JavaScript, if you do:

var myvar = 5;

Then it will be local to that file, however if you accidentally forget var and just do:

myvar = 5;

Then it becomes global.

Is there any good solution to fixing this, it seems to me that the defaul开发者_StackOverflowt should have been that it is local, and you should do something like global myvar = 5 in order to get a global.

There is "use strict"; that I discovered to warn you but I was hoping for a more elegant solution and thought it must exist?


Then it will be local to that file

No, it will be local to that function

however if you accidentally forget "var"… Is there any good solution to fixing this

JS Lint will shout at you for using globals and JS now supports strict mode (although not all browsers have caught up with it).

There is "use strict"; that I discovered to warn you but I was hoping for a more elegant solution

Strict mode is elegant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜