最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

HTML JavaScript Include File Variable Scope - Stack Overflow

programmeradmin4浏览0评论

If I include a JavaScript file in my HTML page, do the variables declared in my JavaScript file also have scope in my <script /> tags in my HTML page? For example, in my included JS file, I declare a variable:

var myVar = "test";

Then inside my HTML page, what will this produce (if it's after my include script tag)?

alert(myVar);

If I include a JavaScript file in my HTML page, do the variables declared in my JavaScript file also have scope in my <script /> tags in my HTML page? For example, in my included JS file, I declare a variable:

var myVar = "test";

Then inside my HTML page, what will this produce (if it's after my include script tag)?

alert(myVar);
Share Improve this question asked Apr 15, 2009 at 14:09 Brandon MontgomeryBrandon Montgomery 6,9863 gold badges49 silver badges71 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

If you declare the variable outside of any function as

var myVar = 'test';

or at any location as

myVar = 'test';

or

window.myVar = 'test';

It should be added to the Global Object (window) and be available anywhere as

alert(myVar);

or

alert(window.myVar);

or

alert(window['myVar']);

It will produce an alert containing "test".

All variables declared at the top level in JavaScript share the same scope. If you want to use variables in one file that won't clash with another, then you can use an anonymous function to introduce a new scope:

var myVar = "something else";
(function () {var myVar = "test"; alert(myVar)})();
alert(myVar);

edit: As BYK points out, you can expand this into something that resembles a full fledged namespace, by assigning an object literal:

var MyNamespace = (function () {
  var myVar = "something";
  return { alert: function() { alert(myVar) },
           setVar: function(value) { myVar = value } }
})();

When you declare a variable or a function in your code, you're creating a property of window. Consider these examples:

var a = 'Cow';
alert(window.a); // Cow
alert(this.a); // Cow
alert(a); // Cow

If you declare a variable inside a function, your variable won't be accessible from outside of it unless you add it to the window object:

function lalala() {
    alert(a); // still Cow
    a = 'Pig'; // We're tired of cows by now. Let's make it a pig.
    var b = 'Sheep';
}
lalala();
alert(a); // Pig
alert(b); // undefined, since b is declared in the lalala scope

Thus, your example would alert test.

发布评论

评论列表(0)

  1. 暂无评论