I have a doubt
My Code :-
function f() {
var g = function()
{
return 1;
}
return g;
};
How do I can call g? I want to return 1 once and again I want to return g.
I did a Research I found a solution
How we can call g is:-
f()();
Why this is ?? What is f()();
in JavaScript. why not we can achieve this using f.g
or something.
How can I return g from the function f ??
Please clarify my doubts ?
Nested functions A function is called “nested” when it is created inside another function. It is easily possible to do this with JavaScript. Here the nested function getFullName() is made for convenience. It can access the outer variables and so can return the full name.
we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; };
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
How can I return g from that function?
You are returning g
from "that function", assuming "that function" is f
. Since f
returns a function you are able to invoke the return value with f()()
. It's pretty much the same as this:
var returnedFunction = f();
returnedFunction();
why not we can achieve this using
f.g
or something?
Because g
is not a property of f
. I'm not entirely sure what you're aiming for, but perhaps you wanted f
to be a constructor, and instances of it to have a method g
?
function f() {
// Constructor function
}
f.prototype.g = function () {
// Method
};
var myF = new f();
myF.g(); // Now `g` is accessible as a property of the instance
You could alternatively have intended g
to be a static property of f
:
function f() {
// JS has first-class functions so you can set properties on them
}
f.g = function () {
// Static method of `f`
};
f.g();
Your f()
is returning a function and the second ()
means you are calling that function.
Think of it like this
var g = f();
g();
Except when you do f()()
you are basically inlining the variable.
If you wanted to call it using f.g()
you would need to declare f
as an object or add g
as a property.
function f() {
this.g = function() {
return 1;
};
}
new f().g();
or
var f = {
g: function() {
return 1;
}
}
f.g();
But I am not 100% what it is you are trying to accomplish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With