What is the scope of this object

I have the following code snippet that uses 'event'. My fellow developers claim that the scope of the "var event" is limited by the "if" condition. It's true. How can I make this code better

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
    }
  }
+3
source share
3 answers

This is not true. In JavaScript, there is no block region, only a function region * . All variables entered into the function rise to the top of the function.

So this code:

function prepForDrag(obj, event) {
    if (event = "undefined") {
        var event = obj || window.event;
    }
    // ...
}

interpreted as follows:

function prepForDrag(obj, event) {
    if (event = "undefined") {
        event = obj || window.event;
    }
    // ...
}

, event , event , . , JavaScript Scoping and Hoisting.

.

  • = ==. true.

  • , , typeof event == 'undefined'.

, . ? obj -, event? , . , :

function prepForDrag(e) {
    var event = e || window.event;
    // ...
}

* NB: let statement, JavaScript 1.7, , Firefox.

+10

event prepForDrag, .

if :

if(event= "undefined")

"undefined" event true. ,

if (typeof event == "undefined")

( , )

function prepForDrag(event) {
    event = event || 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
    }
}

, eval ing document.${formName}?

+6

JavaScript does not have a block scope (except for the exception variable inside the block catch), so in your case the variable eventhas a scope. The best you can do is reassign to a eventnew value or perhaps use a different variable name.

+2
source

Source: https://habr.com/ru/post/1764498/


All Articles