Reputation: 578
function(e){ if(e.which==='37'){ // } }
After I search for "how does this e
or event parameter work" on the internet for while, I still did not find an answer.
Assume e
has not been defined before this function call; what will e
become after this function call? An Object?
Does the which cause it to become a object?
Can we pass a undefined variable into a function in JavaScript? What is expected to happen if I did so?
Upvotes: 0
Views: 97
Reputation: 115910
The variable e
is a parameter of the function. Forget about events for a minute and consider this function:
function doStuff(e) {
alert(e.which);
}
This function accepts something called e
and alerts the which
property of that value. Note that this function is the same as:
function doStuff(firstParam) {
alert(firstParam.which);
}
This shows that we can call the parameter anything we like, but we've chosen to call it e
.
You could invoke the function directly like:
doStuff({ which: 46 });
doStuff({ which: 57 });
doStuff({ which: "Bob" });
Each of these invokes doStuff
and passes in some object with a which
property, which the doStuff
function body refers to as e
.
Now suppose we use doStuff
as an event listener:
document.addEventListener("keypress", doStuff);
This tells the browser to invoke doStuff
every time the user presses a key. What gets used as the e
value depends on which key caused the keypress
event to occur.
what will e become after this function call?
e
does not exist outside of this function. JavaScript scope is function-based, and e
is limited in scope to this function, since it is a formal parameter of the function.
Does the which cause it to become a object?
No, the which
is simply an object property of the Event object that is supplied as the e
parameter. When a function is invoked as an event listener, the value passed as the function 's first parameter is always an object (specifically, an Event object, with details about the event).
Upvotes: 1
Reputation: 943108
Assume e has not been defined before this function call... what will e become after this function call?
Nothing. It will remain undefined
.
Normally, you would use a function like this as an event handler. In that case, the event object (the use of which
implies a keyboard event if you want to be specific) is created by the code that calls the function.
For the most part, that code will be built into the browser and not written by you directly.
Upvotes: 0