[javascript] jQuery make global variable

How to pass function a_href = $(this).attr('href'); value to global a_href, make a_href="home"

var a_href; 

    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }

console.log(a_href);  
//Output is undefined 

This question is related to javascript jquery

The answer is


You can avoid declaration of global variables by adding them directly to the global object:

(function(global) {

  ...

  global.varName = someValue;

  ...

}(this));

A disadvantage of this method is that global.varName won't exist until that specific line of code is executed, but that can be easily worked around.

You might also consider an application architecture where such globals are held in a closure common to all functions that need them, or as properties of a suitably accessible data storage object.


set the variable on window:

window.a_href = a_href;