passing an anonymous function to another function in Javascript - javascript

I understand you can pass a function as an argument to another function like so
var fn = function(){alert('Hello')}
function outer(a,fn){
fn();
}
How can you pass an anonymous function to another function and have it invoked within the function after taking a parameter from the outer function?
function outer(function(x){alert(x);})
{
var xVar = "foo";
//..would liked to pass xVar to the anaonymous function
//passed as a param to the function so that "foo" is displayed as message...
}
Please note changing the signature of outer would be the last choice.

You're confusing function invocation (calling a function) with function declaration (defining a function). Here's how do what you ask:
// declare the outer function
function outer(func)
{
var xVar = 'foo';
func(xVar)
}
// now invoke it
outer(function (x)
{
alert(x);
});

Related

How to call a function expression which being nested inside another function?

How to call a function expression which being nested inside another function ?
let a = function() {
//do something
let b = function() {
console.log('Hello World!')
}
}
a();
There are different ways to define functions in Javascript like Function declaration, Function expression and Arrow functions.
Function declaration can be defined as follow :
function a() {
alert("a");
}
and you can call it by its name a()
and the second is function expression which can be defined in two ways:
//Anonymous Function Expression
let anotherFn = function(){};
//Named function Expression
let anotherFn = function b() {};
you can only call the above function as anotherFn()
In anonymous function expression, the function is assigned to a variable and that function can only be called by the variable name. An anonymous function expression doesn't have any name.
However, you can also provide the name to the function expression. It is useful when you want to refer the current function inside the function body, e.g. in case of recursion. But the name is only accessible within the function body and can't be used to invoke the function outside.
That's why you are getting error b is not defined.
See function expression:
Syntax
var myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
statements
};
[...]
name
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
Note the last sentence.
why should i use variable to call a function and put parentheses after it?
You can define functions either as a function statement or as an expression. See var functionName = function() {} vs function functionName() {} for more information.

Learning Javascript Functions Scope

var greet="Hello";
function Greet(Greetings=greet)
{
console.log(Greetings);
}
function Greet_Friend()
{
var greet="Hi";
Greet();
}
Greet_Friend();
I am having some problems in understanding the scopes in JavaScript?
On Running this code i get "Hello" as output but I need "Hi".
I know your logic, you want to use Greet() to log a variable that in other function, right?
var greet="Hello";
function Greet(Greetings=greet) {
console.log(Greetings);
}
function Greet_Friend() {
var greet="Hi";
// you forgot to pass the local variable to the log function
Greet(greet);
}
Greet_Friend();
In reality, we don't invoke Greet() directly in the Greet_Friend,we do this
var greet="Hello";
function Greet(Greetings=greet) {
console.log(Greetings);
}
function Friend() {
var greet="Hi";
return greet;
}
Greet(Friend());
Or use callback:
var greet="Hello";
function Greet(Greetings=greet) {
console.log(Greetings);
}
function Greet_Friend(callback) {
var greet="Hi";
callback(greet);
}
Greet_Friend(Greet);
var
The function Greet sets the default value of Greetings as greet.
var greet="Hello"; is a global variable thus the value of greet is always "Hello" unless overrridden during function call.
In your function Greet_Friend you call the function Greet without supplying any parameters, thus the function Greet takes the global variable with the value of Hello.
To get the value of "Hi", you would need to pass the local variable greet to the function Greet as follows
function Greet_Friend()
{
var greet="Hi";
Greet(greet);
}
Then call Greet_Friend as follows:
Greet_Friend()
No Global Variables
//greet takes a string as a parameter - you can call it anything, but no equals sign
function greet(str) {
console.log(str)
}
//greet_friend initializes the variable and sends it to greet
function greet_friend() {
var myGreeting = 'Hi';
greet(myGreeting);
}
function greet_friend(); // "hi"

function inside function with same name in javascript

If I pass function to a function with same function name and handler name, which one will get precedence ? and how to access each of those two inside function in case in need to do recursion as well as refer to the passed function. See below code.
var f1,f2;
(function f(f){
return typeof f(f2); /*please check below comments for output of this line*/
})(function(f1){ return 1; });
/* this will call the passed function,why not recursion will not happen here? */
The function parameter gets precedence over the function's own name. If you shadow or overwrite a variable, you can't access it (unless it's a shadowed global).
Solution is to use different names.
The recursion doesn't happen simply because the argument of the function get precendence than the function itself. here is an example that shows it:
(function f (f) {
return f.name;
}) (function funcName () { }); // this will return funcName
if we change the name of the argument to f1, f will become the reference of the function itself
(function f (f1) {
return f.name;
}) (function funcName () { }); // this will return f
I see that you use jquery. So I want to ask where do you have declared your functions? inside
<script type="text/javascript">
$(document).ready(function(){
function f(){
return 'this is local function inside anonymous function, so it's invisible for recursion in aside of current document ready'
}
});
//or here?
function f(){
return 'this function is a window object property, and must be visible for recursion';
}
</script>

Assign a function with custom parameters without calling the funcion

I've a function A which accepts at run-time another function B as parameter and calls it. The problem is the function B needs some parameters, but I don't know how to pass the function B, with parameters, to the the function A.
Example:
function callerFunction(c)
{
alert("The caller is calling the function!");
c(c.arguments);
};
var a = "hello";
function thisOne(d)
{
d = "I changed my way";
alert(d);
};
callerFunction( /* I NEED TO PASS THE 'thisOne' with the parameter/variable 'a' here, and then call it inside 'callerFunction' */);
Just pass a closure:
callerFunction(function() { thisOne(a); });
And call it as c(), not c(c.arguments).
Note that this anonymous function will reference the a variable, not the value a had at that moment. So if callerFunction() was to store this function object and call it later, if you changed the value in a between passing the anonymous function and the time it is called, the value of a from the perspective of the anonymous function would have changed:
var a = 1;
var fn = function() { console.log(a); };
fn(); // Logs 1
a = 2;
fn(); // Logs 2

Passing function by variables

I've this situation:
<script>
var cb;
function doSomething(c) {
cb = c();
}
cb();
</script>
But it doesn't work. I want to set a variable as function, to make a callback called by other functions.. Some ideas?
c() executes the function and returns a value, you need to pass a reference to it:
cb = c
Also, you should call the function doSomething(func) to make the assignment.
doSomething(function(){ alert('hello'); });
cb(); // "Hello"
But if what you want is a callback then you don't need a global variable:
function doSomething(callback) {
// do something
if (callback) callback();
}
When you run the function with another function as parameter the callback will run.
You need to assign cb first with your function:
<script>
var cb;
function doSomething(c) {
cb = c;
}
var myFunc = function(){
window.alert("test");
}
doSomething(myFunc);
cb();
</script>
And if you do cb=c(); you will execute function c instantly and return the value to cb if you want the variable cb as the result of c, do like this. otherwise, assign without running it.
You have 3 options to set a variable to a functiion
var fn = functionname;
var fn = function(param){}; this will be an anonymous function
var fn = function FunctionName(param){}; this will be a named function, comes in handy when debugging, since it will present you with a function name (console.log(c);
You cann call it like var returnVal = fn(); or pass it to a function var returnVal = myFunc(fn); where myFunc calls the param, let it be inFn it like inFn();
What might be interesting to note:
Since such a function is related to the global context, you can bind an object to it alter its scope. That gives you the possibility of thisreferencing the bound object. (Be aware, bind is not supported by all browsers as it is defined ECMAScript 5, but there are quite some polyfills out there.)
fn.bind(object);
Or call it in another context with fn.call(object, param1, param2) or fn.apply(object, [param1, param2]). Nice write up on this Link to odetocode.com/blog.

Categories