- 1
Donât understand anonymous functions. Help?
So I get adding the event listener, then passing it click. I know that add event needs to be passed 2 things. The second being a function. But I see things as if there are wires. I donât know where the empty function parentheses wire goes. HTML <h1 class=âseanTitleâ><\h1> JS //Assign selector to variable. let seanTitle = document.querySelector("h1.seanClass"); //Create function to take effect. seanTitle.addEventListener('click', () => { //Add styling you want. seanTitle.style.color = "blue"; });
3 Answers
+ 4
So basically anonymous functions are as it suggests âFunction without any nameâ.
Now where we use it?
Well its used at a place where you have a function that you only need to use once .
so its really a good idea to use anonymous functions as callback function as its only gonna be used once.
the ()=>{} is just a short hand of function(){}
so you can very well use :
seanTitle.addEventListener('click',function(){
seanTitle.style.color='blue';
});
instead of :
seanTitle.addEventListener('click',()=>{
seanTitle.style.color='blue';
});
+ 3
understanding comes with doing.
Take it as it is, use it often...
u will understand
+ 2
about 3 function declaration ways (+ variants):
// named declaration
function namedFunc() { }
// can be assigned to variable:
var anyName = namedFunc;
// hoisted: can use them sooner than declaration
// keyword expression (named or not)
var kwFunc1 = function funcName() { };
var kwFunc2 = function() { };
// arrow expression (anonymous)
var arrowFunc = () => { };
// NOT hoisted: can only use them after (in program flow) declaration
arrow functions can never bind 'this' object... so slightly difference in using as event listener callback: cannot access target object with 'this'
however, allow access of original 'this' target object if declared at scope with 'this' object (constructors, methods)
// object literal function declaration other way
var o = {
methodName: function() { },
};
or
var o = {
methodName() { },
};
act as keyword declaration: 'this' inside function is the object on wich is attached the method
as variable can store function, argument also: callback used as event listener