On about line 18, make the anonymous function with the code 'window.didExecute = true' execute.
var anonymousFunction = function(){};
(function(){window.didExecute=true;})
doesn't work, why?
Because the function is never executed. Use an immediately invoked function expression:
(function(){window.didExecute=true;})();
The () at the end is what actually makes it a function call, resulting in the body of the function executing.
If you weren't using anonymous functions, your code would be the same as doing:
function foo() {
window.didExecute = true;
}
Then never calling foo().
Related
I am trying to understand how an anonymous function inside of a callback function is invoked.
For example:
const callbackExample = function(param, callback) {
console.log('This is an example of a callback function');
callback(param);
};
callbackExample('What', function(param) {
console.log(param);
})
My question is how does a anonymous function get invoked? If I substitute the callback to equal the anonymous function below.
Is the callback being substituted for the anonymous function.
Does the callback === function(param) { console.log(param) }
What I mean is I cannot invoke the function like this.
function() { console.log('Not') } ();
There are only three ways to declare and invoke a function.
assign a anonymous function a name: function expression
give a function a name: function declaration
Immediate Invocation function express
My theory is when not using a function express or function declaration for the callback function then Javascript parses the code and detects a anonymous function and uses iife to invoke the anonymous function.
I cannot find anything on the internet nor an api that describes what is happening behind the scenes, so I ask can somebody explain this to me.
IIFE (immeadiately invoked function expression) is just a name coined by the community for this specific construct:
(function() { /*...*/ })()
It's a function expression, that is directly followed by a function call to that function. That's it. You don't have an IIFE in your code.
My question is how does a anonymous function get invoked?
Functions get invoked using a reference to them, their name is just a debugging feature (and it's a reference to the function itself inside the functions body). Functions don't need a name:
let test = function /*irrelevant*/ () { };
let test2 = test;
test(); test2();
If you use a function declaration, the name is not only used as the function name, but also as the name of a variable that references the function:
function named() { }
is barely equal to (let's ignore "hoisting" here):
var named = function named() { }
If you invoke a function using a function expression as one of it's arguments:
function called(reference) { }
called(function irrelevant() { })
then the function expression gets evaluated, a function gets created, and a reference to it gets passed to the called function as an argument, which can then be accessed using the reference variable.
i want to pass a function to another function as a parameter.
I want to do that because the latter function calls an async Jquery method and AFTER that gives a result back, i want some javascript code executed.
And because this function is called from multiple places, i want the code to execute (after the async Jquery code gets executed) to be passed in the function.
Makes sense? i hope :)
Now what is see is that the order in which the code is executed is noth what i want.
I've simplified the code to this code:
$('#AddThirdParty').click(function() {
var func = new function() {
alert('1');
alert('2');
alert('3');
}
alert('4');
LoadHtml(func);
alert('5');
});
function LoadHtml(funcToExecute) {
//load some async content
funcToExecute;
}
Now what i wanted to achieve (or at least what i thought would happen) was that alert4 would fire, then the loadhtml would fire alert1, alert2 and alert3, and then the code would return to alert5.
But what happens is this: alert1, alert2, alert3, alert4, alert5.
Does anyone know what i'm doing wrong and why this is the order in which the code is executed?
It looks like the alert1..alert3 gets executed when i define the new function(), but why doesn't it ALSO get executed when i call it from the LoadHtml function?
$('#AddThirdParty').click(function() {
var func = function() { // NOTE: no "new"
alert('1');
alert('2');
alert('3');
}
alert('4');
LoadHtml(func);
alert('5');
});
function LoadHtml(funcToExecute) {
//load some async content
funcToExecute(); // NOTE: parentheses
}
Two errors: the syntax for anonymous functions does not include the keyword new; and JavaScript requires parentheses for function calls, even if functions do not take any arguments. When you just say funcToExecute, that is just a variable giving its value in a context where nothing is using that value (kind of like writing 3; as a statement).
You might notice that you already know how to use anonymous functions: you did not write $('#AddThirdParty').click(new function() ...);
$('#AddThirdParty').click(function() {
var func = new function() {
alert('1');
alert('2');
alert('3');
}
alert('4');
LoadHtml(func);
alert('5');
});
function LoadHtml(funcToExecute) {
//load some async content
funcToExecute;
}
The new keyword creates an object from the function. This means the function (which is anonymous) gets called immediatly. This would be the same as
var foo = function() {
alert("1");
alert("2");
alert("3");
}
var func = new foo();
This means your creating a new object (not a function!) and inside the constructor your alert 1,2,3. Then you alert 4. Then you call LoadHtml which does nothing, then you alert 5.
As for
funcToExecute;
The funcToExecute is just a variable containing a function. It actually needs to be executed.
$(document).ready(SetupButtonClicks());
function SetupButtonClicks() {
$('#btnJavaPHP').click(DoPHPStuff());
}
function DoPHPStuff() {
//stuff
}
I have this code in my javascript file, when I debug it I see it call SetupButtonClicks() like it should but after that is done it calls DoPHPStuff(). DoPHPStuff() should only be called when btnJavaPHP is clicked. What am I doing wrong?
Change your SetupButtonClicks function:
$('#btnJavaPHP').click(DoHPStuff);
The way you've got it coded, you're telling Javascript to call the function, not to use it as the "click" handler. The parentheses are an operator that causes a function to be called.
Remove the ().
By writing $(document).ready(SetupButtonClicks()), you are calling SetupButtonClicks and passing its return value to ready.
Similarly, by writing $('#btnJavaPHP').click(DoPHPStuff()), you are calling DoPHPStuff (immediately) and passing whatever it returns to click().
You need to pass the functions themselves by writing $(document).ready(SetupButtonClicks) and $('#btnJavaPHP').click(DoPHPStuff).
function DoPHPStuff() {
//stuff
}
function SetupButtonClicks() {
$('#btnJavaPHP').click(DoPHPStuff);
}
$(document).ready(SetupButtonClicks);
With the exception of a function declaration, a pair of parentheses following a function's identifier causes the function to execute. Examples:
// function declaration; function not executed
function SetupButtonClicks() {
}
// function executed
SetupButtonClicks();
// function not executed
SetupButtonClicks;
I have a javascript which I didn't write but I need to use it ..
function function1()
... body..
and at the end
I have this
'callback': 'getListCallback'
}
What does this callback mean and getListCallback = function(obj) is another function, does this mean that results from function1 are returned to function getListCallback?
Tnx
A callback function is a function that is going to be called later, usually when some event occurs. For example, when adding an event listener:
function callback(){
alert("click");
}
document.body.addEventListener("click", callback, true);
In many cases you pass the callback function as an anonymous function:
setTimeout(function(){alert("It's been 1 second");}, 1000);
The code getListCallback = function1(obj); will not call getListCallback with the results of function1(obj). It will store whatever function1(obj) returns into getListCallback. If function1 returns a function, then you can call that function later, like so:
function function1(obj){
return function(){
alert("getListCallback was called. obj = "+obj);
}
}
getListCallback = function1(1);
getListCallback();
Yes, it should mean that
normally a callback function means a function which will call after current function execution finished.
This
getListCallback = function(obj){// do something} is like assigning this "function(obj){//....}" to a variable which can use in any place where you need to use that function.
How can I call the Jquery Function From other javaScript Function (Not
from jquery function)
i.e
I have written some Jquery code like below
$(document).ready(function()
{
function func1(){
// Do Something.
}
});
Now I want to call the func1() function from other JavaScript Function
i.e Say an Example
function callJqueryFunction(){
**func1();**
}
The above javaScript function calling not work
but If do the same code inside a
$(document).ready(function()
{
function func1(){
// Do Something.
}
**func1();**
});
Its Work fine.
So what can I do for call the function which is inside a Jquery code
format.
this has nothing to do with jquery in general, it's just a scoping issue
function foo()
{
function bar() {
....
}
bar() // Ok
}
bar() // Not OK
function 'bar' is "local" in foo and is not visible outside of it.
if you want a function to be used in different contexts, declare it globally.
Isn't func1 scoped inside that ready function? If you declare func1 outside of ready it should be available to other javascript code just as any other function.
So:
$(document).ready(function()
{
func1();
});
function func1()
{
// Do something
}
function SomeOtherJavascriptFunction()
{
func1();
}
The function func1 is defined in the scope of the parent function. If you don't need this, you can simply move the definition outside (I expect in case of $(document).ready you don't really need it). Otherwise you will need to pass/store the function reference somewhere, and use that to call it.
You can do something like this
var funcToCall;
$(document).ready(function()
{
funcToCall = function func1(){
// Do Something.
}
});
funcToCall();