Strange JavaScript behaviour? - javascript

I have a simple function that calls other functions:
function update() {
updateMissiles();
updatePlayer;
updateTurbines();
}
They are similar to each other in every way except updatePlayer will not run if I put brackets on the end of it. This doesn't break any code but I'm still curious why it does that?

I'm guessing there's an Exception in the updatePlayer method and since you're not calling it in the code you pasted above, you're not getting the Exception.
I would open up the Developer Tools for whatever browser you're using and see if there are any JavaScript Exceptions being thrown.

You are confused. updatePlayer; doesn't invoke the updatePlayer function. updatePlayer(); does. Something else is going on in your code.

Without knowing more it's impossible to pinpoint exactly, but as a best guess - in the scope of the update function, the updatePlayer variable is not a function.
Try logging or debugging your javascript to find out what is going on.

A function will run only if you put () after it's name.
If you don't put brackets you'll get the function's content.
For example if you have:
function updatePlayer(){ alert('This is a player');}
And call it without brackets:
alert(updatePlayer);
the alerted output will be
function updatePlayer(){ alert('This is a player');}
This is used if you want to use callback functions.

Related

how to execute a javascript code right after a function has been defined?

For example, there is a function like:
function something(a,b,c,d){/*its defined*/}
I would need a javascript code to execute right after the function has been created.
Simply "if(typeof functionName == 'function')" wont do, since that wont execute right after its defined. It would need to be something like an event listener, executing right when it sees the function having been created.
Oh, and I CANNOT edit the function, and can NOT paste javascript right after it. its in an external javascript file I CANT edit.
Why I need this is because I need to overwrite the function right after it is defined, before it is called, but I don't know when it is called, and I probably can't edit that part either. Its probably only created right before it is called.
A sample is below.
(function something(a,b,c,d){
//its defined
})(); // its executed immediately.
This is called IIFE - Immediately Invoked Function Expression

Two confusing statements, which one to use and why?

I am confused about these two statements. Both are giving two different results. For simplification I am not posting full code here. The key point is I want to know the difference between the two. say, I want to invoke a function when I scroll the page. What is the difference between using a parentheses and not using a parentheses in this statement?
window.onscroll=function_Name;
And
window.onscroll=function_Name();
With parenthesis means: run the function and return the result.
Without parenthesis means: use the function itself.
So if you want to bind a function to the "onscroll" event, you do NOT want parenthesis. For example, if your function returns "2", then
window.onscroll=function_Name();
would be the same as
window.onscroll="2";
which wouldn't make sense.
window.onscroll needs to be a function. If function_Name is a function, then the first form would be the one you'd normally use. function_Name() executes the function, so the only way the second thing is legal is if function_Name returned a function as a result (for example, generateScrollHandler might be a good name for such a function-returning function). But if it returns, say, 5, then window.onscroll becomes 5, which makes no sense at all.
The parenthesis used in "window.onscroll()" means that the function is being called by the scroll event, without the parenthesis, the script will not know that it is supposed to run the code, in stead it will try and call a variable, or it will do nothing.

Variable Not Defined, Sometimes

The following code is presented, in the book Head First jQuery.
function lightning_one(t) {
$("#lightning1").fadeIn(250).fadeOut(250);
setTimeout("lightning_one()", t);
}; // end lightning_one
It gets called with this line.
lightning_one(3000);
The observed behaviour is that the lightning fades in and out once, waits 3 seconds, fades in and out again, and then continues to fade in and out. Firebug shows no javascript errors.
I understand why I see what I see. I thought I would attempt to preserve the 3 second interval, so I changed this:
setTimeout("lightning_one()", t); // nothing in the brackets
to this:
setTimeout("lightning_one(t)", t); // t is in the brackets
When I refresh the page, the lightning fades in and out once. Firebug tells me that variable t is undefined.
My question is, if the variable t is not defined after my change, how did the command run without error before I changed it? It still has a variable named t.
More Info
Thank you everyone who wrote comments and answers. For the record, in the "end" folder, the code becomes this:
lightning_one();
function lightning_one(){
$("#container #lightning1").fadeIn(250).fadeOut(250);
setTimeout("lightning_one()",4000);
};
I haven't finished the applicable chapter yet so I don't know if the code change gets suggested later on. As mentioned earlier, this might not be the best book out there. However it's the one I bought and I am learning the fundamentals of jQuery from it.
Because the first argument of setTimeout as a string is eval-ed, meaning that it will looking into the outer scope of the function in which t is not defined. The first one is fine because you don't use any variables in the call, but the second is not because t is not defined outside the scope of the function. It is in fact local.
Advice: Don't use eval at all. In fact, you don't need the string argument. Use a function expression:
setTimeout(function() {
lightning_one(t);
}, t);
This will work:
setTimeout(function () { lightning_one(t); }, t);
I'm pretty sure invoking a function from a String (and letting it get evaluated) is a bad practice that should be avoided.

Complicated way of Javascript function

I observe a different (different for me) way to write function of javascript or jquery,,,you guys kindly guide me about the working of this one.
(function ()
{
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
}());
Truly I'm not understanding (function(){}());.
No one is calling it but it is being called properly.
If any piece of tutorial you guys know, concerned to it, then tell me.
That is a Immediately-Invoked Function Expression (IIFE). In other words, a function that gets executed when defined
Declaring a function without a name is normally used to assign that function into a variable. A useful trick which allows you to pass the entire function around and call it later.
In this case it's not being assigned to anything, but the extra set of brackets after the braces are effectively calling the function immediately.

In JavaScript, what code executes at runtime and what code executes at parsetime?

With objects especially, I don't understand what parts of the object run before initialization, what runs at initialization and what runs sometime after.
EDIT: It seems that parsetime is the wrong word. I guess I should have formulated the question "In the 2-pass read, what gets read the first pass and what gets read the second pass?"
A javascript file is run in a 2-pass read. The first pass parses syntax and collects function definitions, and the second pass actually executes the code. This can be seen by noting that the following code works:
foo();
function foo() {
return 5;
}
but the following doesn't
foo(); // ReferenceError: foo is not defined
foo = function() {
return 5;
}
However, this isn't really useful to know, as there isn't any execution in the first pass. You can't make use of this feature to change your logic at all.
Unlike C++, it is not possible to run logic in the Javascript parser.
I suspect that you're asking which code runs immediately and which code runs when you create each object instance.
The answer is that any code in a function that you call will only run when you call the function, whereas any code outside of a function will run immediately.
Not sure what you ask exactly so I'll just share what I know.
JavaScript functions are "pre loaded" and stored in the browser's memory which means that when you have function declared in the very end of the page and code calling it in the very beginning, it will work.
Note that global variables, meaning any variable assigned outside of a function, are not preloaded, so can be used only after being declared.
All commands outside of a function will be parsed in the order they appear.
JavaScript doesn't really have "runtime", it can only respond to events or have code executed via global timers. Any other code will be parsed and "forgotten".
While JavaScript's direct ancestor is Scheme, JavaScript didn't inherit macros, so the answer is fairly simple: there is never any code run during parse time.
Roughly speaking, Interpreter gets all variables and functions first, and then they get hoisted and executed.
For more detail, I hope these links might be helpful:
http://adripofjavascript.com/blog/drips/variable-and-function-hoisting
https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

Categories

Resources