Why does the following work
var NameSpace = NameSpace || {};
NameSpace.Foo = 2;
But this does not?
var NameSpace = NameSpace || {};
var NameSpace.Foo = 2;
Any insight into the inner workings of the variable deceleration in regards to namespaces would be appreciated.
JavaScript does not have namespaces. Your first line of code is declaring a variable whose name is Namespace, and whose value is an object:
var NameSpace = NameSpace || {};
Then you create a property Foo on the object, and assign a value to it:
NameSpace.Foo = 2;
Bottom line: variables and object properties are different things (among other differences, variables have scope, while properties don't). The var statement is only for declaring variables.
var foo = foo;
works because ECMAscript will decouple this line in away like
var foo;
foo = foo;
under the hood. This concept is commonly called hoisting.
Your second snippet can't work, since we are assigning an object property. The var keyword always implies, that we want to create a variable, a symbol so to speak, within the current Execution Context.
What you could do of course, is
var Foo = NameSpace.Foo = 2;
This would
create the variable Foo in the current context
assign the object property Foo on the NameSpace object
assign both the value of 2
var is reserved for declaring new variables, not modifying existing ones.
Additionally . is an invalid character for a variable name.
Related
I have a situation in which the name of my object will be dynamic..
i.e.
txtGrantAccess_5.GetValue();
i want to know how can I call this dynamically?
e.g.
var abcd = 'txtGrantAccess_5';
abcd.GetValue();
Please note that txtGrantAccess_5 already exists, please can you also avoid the usage of eval in your answer? I have tried understanding other questions almost similar to this but they are not the same thing...
You cannot get local variables dynamically. However, if it's a property of an object you can get it with the [] syntax.
var obj = {};
obj.foo = function() {};
obj.foo();
obj['foo'](); // same as above.
But in this case a local variable cannot be fetched dynamically at all.
var fn = function() {
var foo = '123';
// no way to get foo dynamically.
}
One exception is global variables. In the global scope, local variables are created as properties of the window object:
// global scope, outside of any function.
var foo = function() {};
window.foo();
window['foo'](); // same as above
Just keep in mind that lots of global variables are usually frowned upon, espcially if there is enough that you need to find dynamically like this. You probably just want a container object to keep these values in, like the first example I posted.
Try this snippet
var abcd = 'txtGrantAccess_5';
this[abcd].GetValue();
but be careful with value of "this". If it's in a browser maybe this will help
var abcd = 'txtGrantAccess_5';
window[abcd].GetValue();
How about:
var container = {};
var name = 'dynamicName';
container[name] = new MyObject();
container[name].getValue()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Confused by Javascript's variable scope
For example, this is my JavaScript code:
var foo = 'Originalvalue';
var foo = 'Nextvalue';
alert(foo); // Nextvalue
So then, now I am sure writing var in front of an already-declared variable just simply is nullified and of no use to the program.
But then consider this program:
var foo = 'Originalvalue';
function duhfoo() {
var foo = 'Newbievalue';
}
duhfoo();
alert(foo); // Originalvalue
Then, from the logic explained in my first example, the value should be 'Originalvalue', as there is already a variable called foo. Then why is it like so?
In Javascript there are two kinds of variables: local variables and global variables.
When using var outside of functions you are declaring a global variable and the same happens if you don't use var at all. Writing
foo = "first";
at top level (outside any function) is the same as var foo = "first".
When inside a function however things are different, and the keyword var discriminates between local and global variables:
var foo = "first";
var bar = "second";
function f()
{
var foo = "third"; // local
bar = "fourth"; // global
}
f();
alert([foo, bar]); // output will be first,fourth
In other words when you use var inside a function the variable will be a different one with the same name, visible only by code written inside the boundaries of the function.
Please note that the boundary is determined by the function, and not the braces {...}. If you have nested blocks and use another var declaration inside the blocks the variable will be the same and this is different from what happens in other languages like Java, C or C++.
The only way to create a scope is to define a function (including a function inside a function).
Another very important thing to remember in Javascript (especially if having been exposed to similar-looking languages in which this concept is not present like Java, C or C++) is the idea of "capture"/"closure"...
var foo = "first";
function f()
{
// Local variable
var foo = "second";
function g()
{
// This is the local foo of f, not the global
// one even if there is no "var" declaration
// inside this nested scope
return foo;
}
return g;
}
var nested_function = f();
alert([foo, nested_function()]); // output will be first,second
Basically a local variable can "outlive" the function that defined it, by being used by other functions that are said to "capture" that variable. A function that captures one or more variable is called "closure".
In other words a local variable is only visible inside the body of the function, but it may live longer than then function like it happens for the local foo of last example in which the variable survived after returning from f because it has been captured by closure g.
well variable foo inside duhfoo clearly states that its scope is duhfoo() method and not global.
Because
(From MDN)
var has the following properties
function-scoped
hoist to the top of its function
redeclarations of the same name in the same scope are no-ops
Please read this for more information on this subject.
What's the difference between declaration, definition and initialization? Example:
// Is this a declaration?
var foo;
// Did I defined object in here (but it is empty)?
var foo = {};
// Now that object is initialized with some value?
var foo = {first:"number_one"};
The first example is a declaration. You have declared a variable with the identifier foo. You haven't given it a value yet, so it will be undefined:
var foo;
console.log(foo); //undefined
The second example is a declaration and an assignment. You have assigned an empty object literal to the variable with the identifier foo. As noted in the comments, this is effectively short for:
var foo;
console.log(foo); //undefined
foo = {};
console.log(foo); //Object
The third example is another declaration and another assignment. You have assigned a different object literal to foo.
Edit (see comments)
The behaviour of your code is slightly different depending on whether you intended each example to run as an independent program, or as written (one program).
If you treat is as it's written:
Because variable declarations in JavaScript are hoisted to the top of the scope in which they appear, redeclaring variables has no effect. So the first line declares a variable foo.
The second line assigns an empty object literal to foo, and the third line assigns a different object literal to foo. Both of these assignments apply to the same foo.
What effectively happens is this:
var foo;
foo = {}; //No `var` keyword
foo = {first:"number_one"}; //No `var` keyword
If you treat each line as a separate program:
The first program declares a variable named foo. It's value is undefined.
The second program declares a variable named foo, and then assigns an empty object literal to it.
The third program declares a variable named foo and then assigns an object literal with one property to it.
You got it right.
var foo; // Is this a declaration ?
Yes, you declared that there's a variable named foo, but didn't define foo (so foo is undefined).
var foo = {} // Did I defined object in here (but it is empty) ?
Yes, now you "defined" foo... it has a value, it is no longer undefined. var foo = 5 also counts as "defining" it.
var foo = {first:"number_one"} // Now that object is initialized with some value ?
You could say that it's "initialized," but that's really just semantics. "Declared" and "defined" are a bit more meaningful.
Run the code below:
var foo;
console.dir(foo);
var foo = {};
console.dir(foo);
var foo = {first:"number_one"};
console.dir(foo);
When you declare a variable with var foo; you actually ensure that it will belong to the scope where you've defined it. What you call definition and initialization is in fact a value assignment.
Consider following piece of code as an example:
(function () {
// definition
var foo;
function assignFoo(x) {
// assignment
foo = x;
}
assignFoo(5);
console.log(foo);
})();
To say, you're not always supposed to assign value within the scope of definition. But it is the most common use case which is usually accomplished with var foo = 5.
Thats it.
foo = "foobar";
var bar = function(){
var foo = foo || "";
return foo;
}
bar();`
This code gives a result empty string. Why cannot JS reassign a local variable with same name as a global variable? In other programming languages the expected result is of course "foobar", why does JS behave like that?
That's because you declared a local variable with the same name - and it masks the global variable. So when you write foo you refer to the local variable. That's true even if you write it before the declaration of that local variable, variables in JavaScript are function-scoped. However, you can use the fact that global variables are properties of the global object (window):
var foo = window.foo || "";
window.foo refers to the global variable here.
Once interpreter sees var foo it assumes foo is a local variable. Why? The answer is simple: because that's how this language has been constructed. (and no, it is not the only language that works this way)
////Creating Object
var Obj;
// init Object
Obj= {};
What's the difference between these
two?
Is it possible to make it into a
single line?
Any Advantages of using like this?
the first declares a variable in the current scope, it does not assign any value to it,thus it is not creating any object, while the second one creates an empty object literal to which you can refer through the global Obj variable.
There are 2 main differences : scoping variables and initializing vs declaring.
ex :
var Obj;
alert(typeof Obj);//='undefined'
//scoping :
function foo(){
obj1 = {};
var obj2 = {};
}
alert(typeof obj1);//='object'
alert(typeof obj2);//='undefined'
// obj2 is visible only in the foo function scope,while
// obj1 is being attached to the global scope, the window object
// you can access obj1 as window.obj1 too
var Obj; is not creating an object, it is declaring the variable Obj.
Obj = {}; is initializing the variable Obj with an empty object.
Of course you can combine it and do it in one go:
var Obj = {};
You basically just have to separate declaration and initialization, if you want to initialize the variable with different values, based on some condition or if the variable should be declared in another scope. For example:
var Obj;
if(something) {
Obj = 'me';
else {
Obj = 'you';
}
var Obj; does not create an object, it declares a variable.
Obj = {}; assigns an empty object to the variable named Obj. If Obj was not previously declared, this implicitly declares the variable in the global scope, since the var keyword is missing (don't do this).
var Obj;
only declares the Obj variable, whereas
var Obj = {};
declares and initializes the Obj variable as an empty object.
Make sure you understand the use of the var keyword here as well. It can be used in declaring and/or initializing variables. The difference between
Obj = {};
and
var Obj = {};
is that the var-less code initializes Obj in the global namespace (often considered a bad practice).
tl;dr: In most cases, it is best to initialize and declare at the same time in the local scope, using the var keyword:
var Obj = {};
Maybe I'm not totally understanding your question, but...
var Obj= {};
Is totally fine.
The first allocates the slot for the variable Obj but leaves it undefined. The second binds a newly created object to the name Obj.
You can do it in one line: var Obj = {};. Doing it in two steps has no real advantages, only risks.
var Obj;
this is not creating an object. it defines a variable;
object is first created and than initialized so this are two key processes that are both necessary to have an object.
This line does not actually create an object. Rather it creates a variable (or a place that could hold an object if you put one in there).
var Obj;
This line, does create an object, and places it into the variable.
Obj = {};
This line "initializes" the object by creating a property and setting it to something.
Obj.Something = null;
Note that by saying
var Obj;
you are not creating the object, merely defining a (in scope of a function local) variable initially set to null
Other than that there's no difference whether you merge it into one statement or not.
If that's all the code you've got, there is absolutely NO difference between this:
var Obj;
Obj = {};
and this:
var Obj = {};
IF that's all the code you've got, with nothing in between modifying the Obj variable. In fact, I'd argue that the second way of doing it would be faster than the two lines above.