How to use global variable inside JavaScript closure?

I wrote a custom menu toggle code like below:

var menu_trigger = $  ('.has-submenu > .nav-link'); menu_trigger.on('click', function(e) {     e.preventDefault();      var this_menu        = $  (this);     var this_menu_parent = this_menu.parent('.has-submenu');     var this_submenu     = this_menu.find('.submenu');      if( this_menu_parent.hasClass('active') ) {         this_submenu.slideUp('500');         this_menu_parent.removeClass('active'); // <--- HERE     } else {         this_submenu.slideDown('500');         this_menu_parent.addClass('active'); // <--- AND, HERE     } }); 

The HTML is like below:

<li class="has-submenu active">     <a class="nav-link" href="#">Parent Menu</a>     <div class="submenu">         <a class="dropdown-item" href="/child-1">Child 1</a>         <a class="dropdown-item active" href="/child-2">Child 2</a>         <a class="dropdown-item" href="/child-3">Child 3</a>     </div> </li> 

Along with them I’m using some CSS to display none, and with the .active class, display block etc.

It’s working just fine. But using CSS method, I’m actually loosing the sliding effect, you know. When the .active class is gone, the CSS triggers, and the submenu is already gone, so there’s no visible sliding effect.

It can be solved by a callback to slideUp() and slideDown() easily. So I tried this:

if( this_menu_parent.hasClass('active') ) {     this_submenu.slideUp('500', function() {         this_menu_parent.removeClass('active'); // <--- HERE     }); } else {     this_submenu.slideDown('500', function() {         this_menu_parent.addClass('active'); // <--- AND, HERE     }); } 

But as you can see the variable this_menu_parent is not correctly called inside the closure, hence it is not working. In PHP, we use the use notation, like function(use global_var) { return global_var * 30 }, but that’s not working for JavaScript.

How can I call global variables inside JavaScript closure?