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 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.
Related
Inside a php file I have a script such as this snippet:
<script>
$(function(){
$("#tabs_<?php echo $keyCode ?>").tabs();
var x = document.getElementById("bkhmode_<?php echo $keyCode ?>");
var mode = x.value;
setcont_<?php echo $keyCode ?>(mode);
});
</script>
I want to remove this piece of code along with many other lines like it into a separate JS file to take advantage of caching BUT I have been unable to find the equivalent of a DEFINE command to allow me to replace the php echo.
I would like to
DEFINE KEY_CODE = 'somevalue';
then the snippet would look something like this:
<script>
$(function(){
$("#tabs_KEY_CODE").tabs();
var x = document.getElementById("bkhmode_KEY_CODE");
var mode = x.value;
setcont_KEY_CODE(mode);
});
</script>
Most languages allow for this but I have been unable to find anything equivalent in JavaScript. Any suggestions?
You may set variables to the global window namespace, although it is considered bad practice as it can interfere with other programs, so be careful.
window.KEY_CODE = 'somevalue';
$(function() {
$("#tabs_" + window.KEY_CODE); // Will escape local scope.
});
That should work, although it's common practice to do this with an IIFE.
(function(window, document, $, undefined) {
$("#tabs_" + window.KEY_CODE); // Will escape local scope.
})(window, window.document, window.jQuery);
That helps resolve a lot of namespace issues because they're explicitly defined in the local scope.
You can also use global variables to run a function.
If your function is declared outside of an IIFE (i.e. you've just run it in a global namespace), it's appended to the window element as well. For instance, these are equivalents.
function foo(a)
{
console.log("foo" + a);
}
foo("bar"); // prints "foobar"
window.foo("bar2"); // prints "foobar2"
window['foo']("bar3"); // prints "foobar3"
This is because the browser will assume you're calling window.foo if the local variable foo is undefined. window['foo'] is an identical way of calling window.foo; it accesses the window object, but using a string. So, with that in mind, we can accomplish your variable function call.
window.KEY_CODE = 'somevalue';
window.func_somevalue = function(a) {
console.log("somevalue = " + a);
};
window.func_othervalue = function(a) {
console.log("othervalue = " + a);
}
// prints "somevalue = Hello."
window['func_' + window.KEY_CODE]("Hello.");
You can do this with other objects.
window.KEY_CODE = 'somevalue';
(function(window, document, $, undefined) {
$("#tabs_" + window.KEY_CODE); // Will escape local scope.
var keys = {
'somevalue' : function(a) { console.log(a); },
'othervalue' : function() { console.log('other'); }
};
keys[window.KEY_CODE]("Hello.");
})(window, window.document, window.jQuery);
Is it possible to call the same name variables which set outside of the function?
var a = $(window).width(); // I want to call this variable
if(!$.isFunction(p)){
var a = $(window).height(); // Not this one
alert(a);
}
FIDDLE
In this case, you have actually redefined the value of a. There is absolutely no way of referencing a different variable with the same name, as it just acts as a redefinition.
If you want to declare a global variable you can do so by
window.varname="This is a global variable";
And you can access the same by
alert(window.varname);
Now you can also have a local variable inside a function with the same name
var varname="This is a local variable";
And you can access it normally.
Here's your code so that you can access the global variable not the local one.
var p = ['foo',''];
window.a = $(window).width();
if(!$.isFunction(p)){
var a = $(window).height();
alert(window.a);
}
In a code snippet such as yours, the variable a is being redefined. This is because an if statement doesn't create another scope for variables. However, functions do.
In a case like this:
var a = 0; // global
function doStuff() {
var a = 10; // local
alert(a);
alert(window.a)
}
alert(a);
doStuff();
alert(a);
inside the function doStuff, the variable a is being redefined. This snipped will therefore alert the numbers 0, 10, 0, 0. This proves that the global variable is not redefined inside the function, as printing a after calling doStuff doesn't change the value of a in the global scope.
The variable a outside of the function can be accessed, as any variable not declared in a non-global scope is placed inside the window object. However, if using this snippet (which calls an anonymous function, creating a new scope):
var a = 0; // global
function doStuff() {
var a = 10; // local
alert(a);
alert(window.a)
function() {
var a = 20; // even more local
alert(a);
alert(window.a);
}();
}
alert(a);
doStuff();
alert(a);
you cannot access the value of a inside the doStuff function. You can still access the global variable using window.a.
In your case, however, the if statement does not create a new scope, therefore you are redefining the variable a to the new value $(window).height().
Example:
var a=10;
if(true){
var a=5;
}
alert(a)// it will return a=5;
var a=10;
var a=5;
//both are same way assign value
In js if statement is not scope it visible every where with in function . you have to change the variable name
There is no blockscope in JavaScript (at least up until ES6).
Like you seem to expect from the if block. See
What is the scope of variables in JavaScript?
for an excellent summary of scopes that do exist in JavaScript.
Beware of Hoisting
Furthermore, you shouldn't sprinkle your var declarations through your code, but explicitly put them in the top of your function. That is where Javscript will hoist them anyway:
# so if you have a function like this
var i = 5;
function testvar () {
alert(i);
var i=3;
}
testvar();
# the alert window will contain undefined.
# because internally, it's been changed into this:
var i = 5;
function testvar () {
var i;
alert(i);
i=3;
}
testvar();
Minimize use of the global scope
Read
What is meant by “leaking” into global scope?
And listen to what Doug Crockford has to say about it. Actually, take an hour and watch the whole talk.
You can do it like this:
var p = ['foo',''];
var a = $(window).width(); // I want to call this variable
if(!$.isFunction(p)){
(function(b){
var a = $(window).height();
alert(b);
})(a);
}
No need to use the global scope, just create an anonymous function and call it with a as the argument. Inside the function b is a reference to the a variable outside the function.
It is a good practice not to modify the window object in javascript to write clean and maintainable code.
Less bugs and problems. I mean, never do the window.a thing. Is evil for your code.
No, you can't because of you have redefined the variable name in the same scope and beacuse of the hoisted variables your code will be interpreted by javascript in the following mode:
var p, a;
p = ['foo',''];
a = $(window).width(); // I want to call this variable
if(!$.isFunction(p)){
a = $(window).height(); // Not this one
alert(a);
}
Now you can easly see that the variable a will be replaced and not created
JavaScript has two scopes: global and local. In your example a is in the global scope both times so you are just redefining it.
However you can specify skip a variable in local scope and get the one from global. Consider this example:
var a = 1;
function foo () {
var a = 2;
console.log("var a is: " + window.a);
console.log("local var a is: " + a);
}
foo ();
Will log "var a is: 1"\n"local var a is: 2\n" to the console. This is about as close as it gets to what you need
var abc = new Array();
abc[0] = 'str1';
abc[1] = 'str2';
Use array in this case
Try this (pattern)
var p = ['foo', ''];
var a = function (name) {
return (
name === "height"
? $(window).height()
: (name === "width" ? $(window).width() : name)
)
};
if (!$.isFunction(p)) {
// `$(window).width()` , `$(window).height()`
alert( a("width") + "\n" + a("height") );
}
jsfiddle http://jsfiddle.net/guest271314/2tuK4/
Why "show" method is not able to access "text" variable here ?
// #constructor A
var A = function(){
//alerts some text variable
this.show = function(){
alert("Hello")
alert(text);
}
}
//#constructor B
var B = function(){
//local text variable
var text = "World";
A.apply(this); // "show" method will get attached to B
}
var obj = new B();
//now calling show of B's object.
obj.show(); //returns error.
//Expected output
alerts "Hello"
alerts "World"
//Actual output
alerts "Hello"
ReferenceError: text is not defined
Am I missing something here ?
Shouldn't the "text" variable be accessible to B's "show" method?
Unlike C++ or Java, Javascript doesn't have an implicit this.
If a function (like show) refers to this.foo, then only the value of this depends on how the function was called.
However, if show refers to a variable directly (like foo), then it can mean either:
a local variable, if it's defined using var at the function scope;
a variable from a closure, if the function is being defined inside another function that happens to define it with var (closure gets created at the moment of function definition),
a global variable otherwise.
In your case, the third case applies. show can't access text because it is defined in a totally unrelated scope.
You need to declare the text as property of B constructor this.text = "World"; something like this.
var A = function(){
//alerts some text variable
this.show = function(){
alert("Hello")
alert(this.text);
}
}
//#constructor B
var B = function(){
//local text variable
this.text = "World";
A.apply(this); // "show" method will get attached to B
}
var obj = new B();
//now calling show of B's object.
obj.show(); //returns error.
var foo = 'hello';
var myfunc = function() {
console.log(foo);
var foo = foo || 'world';
console.log(foo);
}
myfunc();
why is the first foo logged to be 'undefined' ?
Because on which line you actually declare a variable using "var" is irrelevant, as long as it remains in the same function. If a function has a var x declared anywhere within it, then any reference to that name is considered local to the scope where it is declared.
Of course, normally you don't reference a variable before it's declared, but consider this snippet:
function foo(a) {
if (a) {
var b = "something";
}
console.log(b);
}
Variable b is local to that function, hence whatever the value of a, usage of b won't accidentally refer to a variable declared on an enclosing scope.
Note: javascript only has function level scoping, it has no block level scoping.
Can someone explain why the alert returns "undefined" instead of "hello"?
window.onload = function() {
var a = 'hello';
alert(window.a);
}
variable 'a' is not part of window in your context.
a is scoped to the anonymous function you've assigned to onload.
you COULD add a as a member of window if you wanted:
window.onload = function() {
window.a = 'hello';
alert(window.a);
}
but i'd suggest against doing so.
"Named variables are defined with the var statement. When used inside of a function, var defines variables with function-scope." - (source)
To be accessible globally, and particularly to make a a member of the window object, alter your code in this way:
var a; // defined in the global scope
window.onload = function() {
a = 'hello'; // initialized
alert(window.a);
}
Or in this way:
var b = 'world'; //defined and initialized in the global scope
window.onload = function() {
alert(window.b);
}