简体   繁体   中英

Is it NOT recommended to use variable outside the scope of event handler?

For jQuery or Javascript in general, is it recommended to NOT use the variable if its outside the scope of the event handler?

Example: Should I avoid doing this?

var $abc = $('#abc');
var $def = $('#def');
$('#myDiv').click(function () {
  $abc.show();
  $def.hide();
});

Instead it's better doing:

$('#myDiv').click(function () {
  $('#abc').show();
  $('#def').hide();
});

Events handlers should know as little as it's possible about your code, and you should also write the less logic as possible inside of them, in the case you're showing it's not a good idea to use variables outside the scope of the function, due that as in any other function, if you miss that variables of your code, everything of your handler will be broken.

In my opinion a better approach will be this.

function doSomething () {
   var $abc = $('#abc');
   var $def = $('#def');
}

//Use .on method for binding events, avoid shortcuts.
$('#myDiv').on("click", doSomething);

Here the handler will call a function that has scoped variables, avoiding writing logic inside the handler, and in case you need to change the function call, you can replace it with other function call whenever you want, demonstrating that this code is easy to follow and mantain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM