I have been using javascript for a while now and am starting to realise how badly I have been using the language. Some more advanced aspects of it are comming to light such as closures, module pattern etc.
Can someone explain how the () operator works when placed at the end of a function i.e. why does it immediately invoke it - i havent seen this before and am puzzled as to how this actually works.
as in:
var myFunct = function() {
alert("here");
}();
The () at the end will immediately invoke the function.
A function is an object. Using function_name
refers to the actual function object. And function_name()
refers to the result of the function. For example:
function foo() {
return 2;
}
typeof foo()
= "number"
typeof foo
= "function"
Javascript functions are first-class objects. They can be stored, passed and returned. Since they're functions, they can also be called.
So you can write this:
var f = function(message) {
window.alert(message);
}
f("Hello, world!");
That creates an anonymous function object and stores it into f
. Then it calls it through f()
.
You can also create an anonymous function object and call it immediately without storing it in a variable:
(function(message) {
window.alert(message);
})("Hello, world!");
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