简体   繁体   中英

How to give a local variable, a global scope in javascript

Below code snippet is Drift chat method to get the email id provided by user in chat.

I am trying to access email id (e.data.email) outside of given function scope by storing it in a global variable data_email .

I have tried three method to make data_email global variable - window , let , const .

window.drift.on("emailCapture", function(e) {
    console.log("user identified as: " + e.data.email);

    window.data_email = e.data.email;
    // let data_email = e.data.email;
    // const data_email = e.data.email;

    ga('send', 'event', {
        eventCategory: 'driftemail',
        eventAction: 'driftemailCaptured',
    });
});

console.log(data_email);

After trying all that I am getting error - Uncaught ReferenceError: data_email is not defined . Please anyone suggest me a work around, i will be very thankful. My goal is to access captured email outside of the given function.

Problem you have there is the fact you are listening to an event. That can happen now, later or never. However you immediately try to console log it.

Given the small amount of information you provided, there could be various solutions to your problem. But one solution is to make:

  • outside function, that function accepts email and sets it as global

  • call that function with email as argument

Something like this

window.drift.on("emailCapture", function(e) {
    console.log("user identified as: " + e.data.email);

    setChatEmail(e.data.email);

    //window.data_email = e.data.email;
    //let data_email = e.data.email;
    //const data_email = e.data.email;

    ga('send', 'event', {
        eventCategory: 'driftemail',
        eventAction: 'driftemailCaptured',
    });
});


function setChatEmail(email) {
  window.data_email = email;
}

Further reading:

How to set global variable.

Why are global variables bad.

Your console.log runs before "emailCapture" event is executed. Thats why its giving you undefined, try everything what you want to do after executing this event.

 var data_email;
 var getEmail = function() {
     console.log(data_email);
 };
 window.drift.on("emailCapture", function(e) {
    console.log("user identified as: " + e.data.email);

    window.data_email = e.data.email;
    data_email = e.data.email;
    // const data_email = e.data.email;

    ga('send', 'event', {
        eventCategory: 'driftemail',
        eventAction: 'driftemailCaptured',
    });
    getEmail();
});

You need to initialize window.data_email on top first then mutate it. Because the console.log will run before it's initialized.

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