In the following function:
foo = function(a){
if (!a) a = "Some value";
// something done with a
return a;
}
When "a" is not declared I want to assign a default value for use in the rest of the function, although "a" is a parameter name and not declared as "var a", is it a private variable of this function? It does not seem to appear as a global var after execution of the function, is this a standard (i.e. consistent) possible use?
It's a private variable within the function scope. it's 'invisible' to the global scope.
As for your code you better write like this
foo = function(a){
if (typeof a == "undefined") a = "Some value";
// something done with a
return a;
}
Because !a can be true for 0, an empty string '' or just null.
Yes, in this context a has a scope inside the function. You can even use it to override global variables for a local scope. So for example, you could do function ($){....}(JQuery); so you know that $ will always be a variable for the JQuery framework.
Parameters always have private function scope.
var a = 'Hi';
foo = function(a) {
if (!a) a = "Some value";
// something done with a
return a;
};
console.log(a); // Logs 'Hi'
console.log('Bye'); // Logs 'Bye'
Related
I decided to create a funcB function that I call from funcA. I want all variables from funcA to be available in the funcB so func B can change that variables.
How to modify the code below so it meets my requirements? I doubt passing all variables it the only possible and the best way.
function funcB(){
alert(var1);//how to make it alert 5
alert(var20);//how to make it alert 50
}
function funcA(){
var var1=5;
...
var var20=50;
funcB();
}
var obj = {
one : "A",
two : "B",
fnA : function() {
this.fnB(); // without fnB method result will be displayed as A B, with fnB as C D
console.log(this.one + " " + this.two);
},
fnB : function() {
this.one = "C";
this.two = "D";
}
};
obj.fnA();
this keyword refers to obj object
You can define object with properties and methods inside it. With methods all the variables can be manipulated as you wish, from this example with fnB I'm changing values of properties which are displayed from fnA method
JSFiddle
One way is to drop the var keyword:
function funcB(){
alert(var1);//how to make it alert 5
alert(var20);//how to make it alert 50
}
function funcA(){
var1 = 5;
var20 = 50;
funcB();
}
This will expose them to the global scope so funcB can access them. Notice you can also create the varaibles in the global scope itself, with the var keyword, but both methods will ultimately have the same effect.
Note:
This may not work if there is already a var1 or var20 in the global scope. In such case, it will modify the global value and may result in unwanted errors.
This method is not preferred for official code, and is bad practice Reason
This is not possible as when you declare a variable with the var keyword, they are scoped to the function in which they are declared.
If you avoid the var keyword, they are instead defined as a global variable. This is deemed very bad practice.
I would recommend you read up on javascript coding patterns, particularly the module pattern.
For example:
var myNamespace = (function () {
var foo, bar;
return {
func1: function() {
foo = "baz";
console.log(foo);
},
func2: function (input) {
foo = input;
console.log(foo);
}
};
})();
Usage:
myNamespace.func1();
// "baz"
myNamespace.func2("hello");
// "hello"
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.
I have JavaScript code as below;
var foo = (function() {
//Private vars
var a = 1;
return {
//Public vars/methods
a: a,
changeVar: function () {
a = 2;
}
}
})();
Now I am not sure how the syntax for public vars/methods works ?
Could you please corelate how just "returning" the vars/methods makes them as public ?
Thank you.
The value of the variable foo is actually the value returned by this function. Notice on the last line, the (), indicating that this function is evaluated immediately. By evaluating a function and assigning its return value to a variable, you are able to hide variables inside a local (function) scope, such that they are not accessible outside that scope. Only members on the returned object are accessible, but because any functions inside form a closure with their outer scope, you can still use local (hidden) variables.
An example of this would be to hide some local state and only allow access to it through a method:
var foo = (function() {
//Private vars
var a = 1;
return {
//Public methods
getVar: function () {
return a;
},
setVar: function (val) {
a = val;
}
}
})();
Okay, you've returned an object in the anonymous function, which means that the object is assigned to foo. So you can access the object's properties like foo.a or foo.changeVar, but you can continue to let the private variables exist, within the function's scope. Can't help much without a more specific question.
So when I declare a variable outside the scope of any function, it becomes a property of the window object. But what about when I declare a variable inside the scope of a function? For example, in the following code I can treat x as a property of window, i.e., window.x, but what about y? Is it ever the property of an object?
var x = "asdf1";
function test() {
var y = "asdf2";
}
test();
It becomes a property of the Variable object associated with the function call. In practice, this is the same thing as the function call's Activation object.
I don't believe that the Variable object is accessible to running JavaScript code, though; it's more of an implementation detail than something you can take advantage of.
Access all local variables is a related question here on SO.
In order to declare a JS variable a property of an object you need to either use the new Object(); method or the {} syntax.
var variableName = new Object();
var variableName = {myFirstProperty:1,myNextProperty:'hi',etc};
Then you can assign child objects or properties to said variable object
variableName.aPropertyNameIMadeUp = 'hello';
variableName.aChildObjectNameIMadeUp = new Object();
As such the new variable object is associated with a method if it is within the method call.
Cheers
See following example (I have copy from other question-answer) very nice:
// a globally-scoped variable
var a=1;
// global scope
function one(){
alert(a);
}
// local scope
function two(a){
alert(a);
}
// local scope again
function three(){
var a = 3;
alert(a);
}
// Intermediate: no such thing as block scope in javascript
function four(){
if(true){
var a=4;
}
alert(a); // alerts '4', not the global value of '1'
}
// Intermediate: object properties
function Five(){
this.a = 5;
}
// Advanced: closure
var six = function(){
var foo = 6;
return function(){
// javascript "closure" means I have access to foo in here,
// because it is defined in the function in which I was defined.
alert(foo);
}
}()
// Advanced: prototype-based scope resolution
function Seven(){
this.a = 7;
}
// [object].prototype.property loses to [object].property in the scope chain
Seven.prototype.a = -1; // won't get reached, because 'a' is set in the constructor above.
Seven.prototype.b = 8; // Will get reached, even though 'b' is NOT set in the constructor.
// These will print 1-8
one();
two(2);
three();
four();
alert(new Five().a);
six();
alert(new Seven().a);
alert(new Seven().b);
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.