I have the following code:
(function resize(){
console.log("Ayuda!!")
})();
window.onresize = function(){ resize() }
The message shown in the console.log is just an example, obviously I have something more complex than that, the fact is that when I try to call that function when the screen is resized, it returns the following error:
Uncaught ReferenceError: resize is not defined
I have also tried this:
window.onresize = resize()
But it doesn't work either, I appreciate your comments and answers.
The problem is the scope , because the function
resize()
is inside the parentheses and add()
to the end, what you do is call itIf you remove it
()
and try to access the function outside the parentheses, it still won't workWell, the scope of the function is only inside the parentheses, normally functions like the one you have structured are used to define anonymous functions
What you can do is something like this
They
IIFE
have the characteristic of being executed at the same time they are declared and they are not saved in anyscope
that contains them (they create their own scope). In this case you are declaring the function, executing it at the moment and when calling the functiononresize
the from is consultedscope
,window
but there has not been any assignment of the functionresize
, so it gives you that error that it has not been defined.Here you have more information about the IIFE
If you don't know Js yet, I recommend the great series of books "You don't know Js yet" by Kyle Simpson ( link ) in which he explains in great depth how scopes, closures and other related concepts work.
An anonymous function can be registered in the
onresize
global scope eventwindow
, inside the function scopeIIFE
:In this way, each time the event occurs, that anonymous function will be in the list of tasks, ready to be executed.
Here's a demo, apply a resize to your browser to see the
consola
: