I have the following code snippet which uses’event’
My fellow developers argue that the scope of ‘var event’ is restricted to ‘if’ condition.
Is that true. How can I make this a better code
function prepForDrag(obj, event) {
if(event= "undefined"){
var event=obj || window.event;
}
if (event.altKey) {
showShiftEditable(objCurrentEditRow, nCurrentEditableShift, lCurrentEditableBreak, true);
var thisForm = eval('document.${formName}');
// ...
enableDragState(obj);
disableClickEditHandler(obj); ## remove 'normal' line sched click handling in dd mode
}
}
That’s not true. In JavaScript there is no block scope, only function scope*. All variables introduced in a function are hoisted up to the top of the function.
So this code:
gets interpreted somewhat like this:
As Marcel Korpel‘s pointed out, declaring variable
eventis unnecessary in this case becauseeventis already a local variable since it’s a function parameter. For futher details, read Ben Cherry’s article on JavaScript Scoping and Hoisting.Nevertheless there are two additional problems in your code.
In the condition you used the
=assignment operator instead of the==comparision operator. So the condition always evaluates to true.If you want to check whether a function argument was given, use the
typeof event == 'undefined'statement.And I’m afraid there is even one more issue here. What is the purpose of the condition? Does argument
objanything to do withevent? Modern browsers pass an event object to the event handler function as argument but some do not. To avoid the problem, the following pattern tends to be used:*NB: there is a
letstatement introduced in JavaScript 1.7 that provides block scope inside functions. Currently it’s only supported in Firefox.