Let's say that:
a() {
console.log("i am a")
}
b() {
c() {
//call function a here
}
}
How do I call function a from function c?
functions declared like you are declaring them are hoisted to the top of the scope. a is available globally and can be called by anything inside the same global scope.
I have solved my problem with using an arrow function on parameter of c.
The way your functions are defined shows that c is nested inside of b which effects the scope when the function executes. First, you would have to figure out a way to call function c. Since it is inside of function b, you will first need to call function b to get to function c. Accessing function c is not possible with your code.
The below code would allow you to call function c, which then calls function a.
function a() {
console.log("i am a")
}
function b() {
this.c = function() {
//call function a here
window.a();
}
return this;
}
b().c()
Related
It is interesting, just theoretically, not in real world.
1 - How can I call inside() function from outside?
2 - Is it common practice to create such a structure?
3 - What will be the value of this in inside() function (if it is possible to call from outside)?
var obj = {
method: function(){
console.log('method function called!');
function inside(){
console.log('inside function called!')
}
}
}
How can I call inside() function from outside? -> No, JavaScript has
block level scope, hence anything defined inside function will not
be accessible outside function. It could be called a private
function.
Is it common practice to create such a structure? -> It is. If you
want your function to be hidden from other part of your execution
cycle.
What will be the the value of this in inside() function (if it is
possible to call from outside)? -> Value of this depends on how
the function is invoked. In your case, this will be window if
function is called without any context hence global(window)
context
var obj = {
method: function() {
console.log('method function called!');
function inside() {
console.log(this);
console.log('inside function called!');
}
inside();
}
}
obj.method();
Please have a look at the following JavaScript snippet of code. This has to do with function scoping and hoisting in javascript. I can't call window.innermost() as it is undefined as it's not in scope.
Anyone know another way besides attaching it to the windows object. Windows Object still doesn't work in this case.
function outer(){
function callback() {
window.innermost = function() {
alert("hello from inner most")
}
}
}
(function caller() {
window.innermost(); // this is undefined
}());
You would have to call both the outer and the callback:
function outer(){
var callback = function() {
window.innermost = function() {
alert("hello from inner most")
}
}
callback(); // Call Callback
}
outer(); // Call outer
(function caller() {
window.innermost(); // should work
}());
If both of these functions are not called before you run the anonymous function, then the window.innermost won't be defined (or undefined if you will).
Also, notice that I set callback as a variable, which is an alternative way of defining a function within a function.
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.
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
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();