JavaScript - Declaring Global Scope for Nested Function? - javascript

My attempts at giving global scope to a nested JavaScript function are not working:
//DECLARE FUNCTION B IN GLOBAL SCOPE
function B;
function A() {
//DEFINE FUNCTION B INSIDE NEST
B() {
alert("function B is running");
}
}
//CALL FUNCTION B FROM GLOBAL SCOPE
B();
This is just curiosity -- you are correct that I don't really have any good reason to want to do this.
TIA -- I don't have an SO account to respond to your answers...

function B; will simply generate a syntax error.
You can use a function expression. As functions are first class objects, you can assign a function to a variable:
var B; // declare (global) variable (outer scope)
function A() {
// assign a function to it
B = function() {
alert("function B is running");
};
}
// we have to call A otherwise it won't work anyway
A();
// call B
B();
You could also let A return a function:
function A() {
return function() {
alert("function B is running");
};
}
B = A();
This would make the relation between A and B a bit clearer.
Of course you can always define a global variable by omitting var, but you should use this very carefully. Use as less global variables as possible.
function A() {
B = function() {
alert("function B is running");
};
}
And I bet there is a better way of doing it, depending on what your actual goal is.
More about Functions and function scope.

What about:
function A() {
window.B = function() {
alert("function B is running");
}
}
//CALL FUNCTION B FROM GLOBAL SCOPE
B();

You can do something like this:
function outer() {
function inner() {
// ..
}
window['inner'] = inner;
}
It's a little icky to have a direct reference to "window", so you could do this (from the global context):
(function (global) {
function inner() {
// code code code ...
}
global['inner'] = inner;
})(this);

There appear to be a couple of issues with your code
The first line doesn't appear to be legal Javascript (JSLint agrees). To declare an uninitialized variable use the var B; syntax
The code never calls A to initialize B so calling B() is invoking an uninitialized variable
I'm fairly certain the code to initialize B inside of A is also not legal.
Try the following
var B; // Establish B as a global scope variable
function A() {
B = function() {
alert('B is running');
};
}
A(); // Call the function which will cause B to be initialized
B(); // Run B

You're close, but not completely correct.
You have to define B as a variable and then assign a function to it.
Also run A() before executing B, otherwise B will be undefined. The easiest way of running it is the way that I show in my code example.
These are the smallest amount of changes to your code to make it work as you asked:
var B;
(function A() {
// define function B
B = function() {
alert("function B is running");
}
})();
// call function B globally
B();

Related

How to get local function to read other separate local function?

If you have two local functions.
function a() {
alert("a");
}
function c() {
alert("c");
}
a();
and in each local function, lied another local function.
function a() {
alert("a");
b();
function b() {
alert("b");
c();
d();
}
}
function c() {
alert("c");
function d() {
alert("d");
}
}
a();
From what I understand, both functions a and c are "global" as they are first to show up in javascript. local function b is linked to global a and local d to global c, so local function b can read global function c, but are not able to see local function d as that are not global function but local function inside that global function, so it can no longer see and call local function d.
How do you ensure that function of d() can be read by the function of b();
I apologized if this has already been asked, I can't think of the correct keyword to ask, and try to search for the correct keyword does not quite answer my question. I believe the answer has to do with the return, but I never got that to work much less so use it for the function itself.
https://jsfiddle.net/Necrorifter/x1L90pvh/
Unless I am understanding or reading this wrong?
One method is to have each function return the internal functions. Then call them later on.
function a() {
console.log("a");
b();
function b() {
console.log("b");
_c = c();
_c.d();
}
return {b:b}
}
function c() {
console.log("c");
function d() {
console.log("d");
}
return {d:d}
}
a();
//i made ur code smaller cuz seeing it spaced out spaces out my mind
function a() {
alert("a");
function b() {
alert("b");
c();c(1)();//when the parameter is 1, the function d is returned, then i called the returned function(thus i called d)
}b();
}
function c(dd) {
function d() {
alert("d");
}
if(dd==1){return(d);}
alert("c");
}
a();
//there is no built in help for something like this so yea i pulled a workaround

Simultaneously Declaring Variables and Functions in JavaScript

Can anyone explain why
function x() {
console.log("Hello!");
}
var a = x;
a();
x();
produces
Hello!
Hello!
but this
var a = function x() {
console.log("Hello!");
}
a();
x();
throws an error when you try to call function x? Is the second x function not considered a hoisted function? I tried this in both nodejs and a browser.
What you have in the second example is what's called a named function expression.
Its name is not added to the containing scope, but is accessible within the scope of the function itself:
var a = function x() {
alert(x);
};
a();
This is useful in writing recursive functions or functions that otherwise reference themselves, as it ensures that the name won't get clobbered due to anything that happens outside the function's scope.
It also allows you to create self-referencing functions in places where you can't use a function declaration, such as in an object literal:
var myFavoriteFunctions = {
factorial: function f(n) {
return n === 1 ? 1 : n * f(n);
},
identity: function (v) { return v; }
};
console.log(myFavoriteFunctions.factorial(10));
Your first example is a function statement, which declares a name in its containing scope.
Your second example is a named function expression, which does not.
For more information, see here.

Returning a self executing Function

Say I want to do this:
function z(){return function(){a = 4}
}
function b(){
var a;
c = z();
c();
}
I want to skip the c(); But instead I want to execute the returned function immediatly upon return in the caller scope so I can work with it.
In this example a should get the value 4.
Is there a way?
cheers
You should be able to execute the return function immediately with
z()();
No, that is impossible (without using tricks like eval). You cannot change the scope of the function returned by z.
Your example could be simpler without the closure, what you are asking for is just
function c() {
a = 4;
}
function b() {
var a;
c(); // should change variable a
return a;
}
b(); // is expected to return 4, but does not
You can't alter the scopes of functions, or pass the scope objects (like pointers to the variables). Yet, you can pass an object whose properties will be altered by the function:
function z(obj) {
return function() {
obj.a = 4;
};
}
function b() {
var o = {};
z(o)(); // as mike and others said, this is the same as yours
// - you don't need the c variable
return o.a;
}
b(); // returns 4 now
escaparello did a similar thing, only he did use the object as the thisValue which he did pass to the anonymous function, not to z. I think mine is easier to understand, and makes a better use of the z closure.
Seems very strange, but you want to do something like this?
function z(){
return function() {
this.a = 4;
return this;
}
}
function b(){
var obj = { a : 0 };
var c = z().apply(obj);
console.log(c.a);
}
b();
Try this
function z(){
return function(){
return 4;
}
}
function b(){
var a;
a = z()();
}

call a function in javascript as global function

I have a main function in javascript that is function a() { some code here } and I also have a child function in this main function that looks like
function a() {
function b() {
// some code here
}
}
now I want to call the function b directly. then how to do this.
You can't. You can, however do something like:
function a() {
this.b = function () {
some code here
}
}
And then call it like:
var x = new a();
a.b();
You can also create an object literal with your function:
var a = {
b: function ()
{
//some code here
}
};
And then just say:
a.b();
You could also create a property on the function object itself, and access it that way:
function a()
{
};
a.b = function ()
{
//Some code here
};
And then call it with:
a.b();
You could try explicitly exposing b to the global object like this:
function a() {
function b() {
// some code here
}
window.exposed = b;
}
Don't declare function b inside of function a, just call it like so
function b() {
some code here
}
function a() {
b();
}
There are many solutions here, the only one I think that will suit is to attach the function to the global object so it looks like a declared function. The only difference is that it won't be available until a runs:
function a() {
// Protect against ES5 strict mode, assume function is called as global code
if (typeof this !== undefined) {
this.b = function() { /* whatever */ };
}
}
or perhaps the following suits your coding style better:
function a() {
function b() { /* whatever */};
if (typeof this !== undefined) {
this.b = b;
}
}
Called simply as:
a();
then in ES3 or ES5 non-strict mode, it will work as expected. To overcome ES5 strict limitations where the above will result in a's this being undefined, call a as global code and set its this explicitly:
a.call(this);
or with some other suitable reference to the global object.
I have stayed away from using window since that is less reliable, not least because non–browser hosts will likely not have a window object.

C++ function prototype equivalent in javascript?

So I want to call function B in function A, but function B is fully declared after function A. I know that in c++ we'd use function prototypes on B, but what about javascript?
code:
markerArray = function() {
// some code here
this.array = [];
this.clearArray = function() {
for(var i = 0; i<this.getLength(); i++)
// for loop code
}
this.getLength = function() {
return this.array.length;
}
// some code here
}
these reason why I put this.getLength below is mainly because my coding style/structure is more readable this way
Javascript doesn't care about this requirement. It will simply work as long as Function A isn't called until after the file is loaded. Function A will be defined, Function B will be defined, then Function A can be called using Function B inside of it with no problem.
Not a problem. Function declarations are hoisted to the top of the enclosing variable environment, so they do not need to be declared in order.
A();
function A() {
B();
}
function B() {
alert('B was called');
}
If you meant something else, you'll need to explain it in your question.
It depends on how you declare your functions. If you declare a function via the Function constructor or a function expression, order matters.
a(1); //this call won't work
//function expression of an anonymous function assigned to the variable multiply
var a = function(i) {
b(i);
}
// b is defined using Function constructor
var b = new Function("i","alert('B was called with ' + i)");
a(1); //this call will work

Categories

Resources