Local and global scope of variables in JavaScript - javascript

I have tried reading other posts on the subject but no luck yet. In this code below why doesnt f2() have access to the var defined in f1(). Is not the var "name" a global to the function f2()? Should not f2() see the var "name"?
function f1() {
var name = "david";
function f2() {
document.writeln(name);
}
document.writeln(name);
}
f2(); // does not write out "david".

your f2() is only defined inside f1() scope. you can't call it globally

Javascript is function level scoped, not block scoped. A function has access to it's parent's function variables but not to variables defined in functions within it. You could return f2 from f1 and call it that way
function f1() {
var name = "david";
document.writeln(name);
return f2
function f2() {
document.writeln(name);
}
}
var f2 = f1();
f2();

You need to read up on Javascript Closures.
Here is a version of your snippet which demonstrates how you can access variables from outer function in an inner function (if you want to call inner function globally).
function f1()
{
var name = "david";
return function()
{
console.log(name);
}
}
var f2 = f1();
f2();

Related

Why the result is 'scope is not defined'

I want to know why the result is scope is not defined
function checkscope() {
var scope = "local scope";
function f() {
console.log(scope);
scope = '123' //为什么这里不是全局变量scope,最后结果为什么是scope is not defined
}
return f;
}
var foo = checkscope();
console.log(foo());
console.log(scope)// 结果是scope is not defined
Because you have defined it out of scope i.e. functional scope.
Please define it out of the function scope. So whenever you call your function. The scope value will be changed.
var scope;
function checkscope() {
scope = "local scope";
function f() {
console.log(scope);
scope = '123' //为什么这里不是全局变量scope,最后结果为什么是scope is not defined
}
return f;
}
var foo = checkscope();
console.log(foo());
console.log(scope)/
scope is declared in the function checkscope. It ceases to exist with the } ending that function.
Thus it no longer exists at the point you use it.

JS variable hoisting inside closure

JS hoists all variables within scope so why does this code throw an exception:
(function() {
function i() {
console.log(a.a);
}
i();
var a = { a:1 };
})()
While this one works:
(function() {
var a = { a:1 };
function i() {
console.log(a.a);
}
i();
})()
What behavior of interpreter causes this?
The variable a is already visible, but its value {a:1} is not assigned until the var is reached by the execution. Things are somewhat different for local functions declared with function foo(){...} because the names are bound to the respective functions/closures before the execution starts.
If you call the closure i before assigning a a value you get the problem, however with
(function(){
function i(){
console.log(foo());
}
i();
function foo() { return 42; }
})();
the output is 42 and there's no error.
Note that this is true because the function statement is used... changing the code to
(function(){
function i(){
console.log(foo());
}
i();
var foo = function(){ return 42; }
})();
gives an error because in this case when i() is executed foo is not yet bound to the function (like in your case).

is a javascript function inside of a function globally scoped?

Here is an example of the test that I did:
function f1(var1){
alert('f1 called');
function f2(var2){
alert('f2 called');
}
this.data='something else';
this.f2 = f2;
}
f1.data='something';
f1.f3 = function(var3){
alert('f3 called');
}
console.log(f1); //shows the function
console.log(f1.data); //can have properties attached - cool
console.log(f1.f2(2)); //error: "f1.f2" is not a function
console.log(f1.f3(3)); //this works as expected
It appears that the function f2 inside f1 is local in scope. is there any equivalent way to call a function inside a function like this?
Unfortunately, this is bound to the global scope of window because you haven't instantiated an instance of f1 using new f1();
var f = new f1();
f.f2(); // Now works
Depending on what you are trying to achieve, there are a couple of patterns you can use to access the f2 function outside of f1. You can instantiate an f1 object using new:
function f1() {
this.f2 = function () { console.log('f2'); }
}
new f1().f2() //logs 'f2'
Or you can return the function f2 from the function f1:
function f1() {
return function f2() { console.log('f2'); }
}
f1()() //logs 'f2'
change code to:
function f1 (var1){
alert('f1 called');
};
f1.data='something else';
f1.f2 = function f2(var2){
alert('f2 called');
};

How to create a unique function with its own pointer in JavaScript?

Calling getFunction will return a unique function every time, right?
var getFunction = function() {
var myFunction = function() {
};
return myFunction;
}
var function1 = getFunction();
var function2 = getFunction();
function1 === function2; // false
Yes, every time a function is called, a new scope is created for that run and all variables defined in it are unique and not shared between runs of the function.
Even doing something like the following would have the same result as the inner function is still defined inside of the function's scope and can see the arguments to the outer function.
var getFunction = function() {
function myFunction() {
};
return myFunction;
}
var function1 = getFunction();
var function2 = getFunction();
function1 === function2; // false
This can be visualized as follows. The outer scope holds the three variable allocations and the getFunction invocations will create two new scopes which return a function object defined in that scope.

JavaScript Internals 101: Hoisting variables and functions

Consider the following examples:
var company = 'Apple',
log = console.log;
function f1() {
log(company);
var company = 'Twilio';
log(company)
}
function f2() {
log(company());
function company() {
return 'Zynga';
}
}
function f3() {
log(company());
var company = function() { return 'RIM'; };
}
log(company);
log('---');
f1();
log('---');
f2();
log('---');
f3();
The output from firebug is:
"Apple"
---
undefined
"Twilio"
---
"Zynga"
---
TypeError: company is not a function
So why is hoisting in f3 giving me the error while others are working just fine?
Let's rewrite your f3 function to show what it would look like after variable hoisting:
function f3() {
log(company());
var company = function() { return 'RIM'; };
}
becomes:
function f3() {
var company; // declaration hoisted
log(company());
company = function() { return 'RIM'; };
}
Now you can see that you are attempting to execute an undefined variable, not a function (hence the "not a function" error).
Note that this is difference from the output of f2 because function declarations are hoisted as a unit.
The variable is hoisted, but setting it is not.
The value of company in f3 is not set until after log(company()) is called. You can see the same behavior in f1.

Categories

Resources