如何在javascript中给出局部变量,全局范围

时间:2017-08-03 06:39:44

标签: javascript

以下代码段是Drift chat方法,用于获取用户在聊天中提供的email id

我试图通过将email id (e.data.email)存储在全局变量data_email中来访问给定函数范围之外的three

我尝试data_email方法制作window全局变量 - letconstwindow.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);

Uncaught ReferenceError: data_email is not defined

尝试了所有错误之后 - sp_executesql。 请有人建议我一个工作,我会非常感激。我的目标是在给定功能之外访问捕获的电子邮件。

3 个答案:

答案 0 :(得分:1)

你遇到的问题是你正在听一个事件。这可能发生在现在,更晚或永远。但是,您立即尝试控制登录。

鉴于您提供的信息量很少,您的问题可能会有各种解决方案。但一个解决方案是:

  • 外部功能,该功能接受电子邮件并将其设置为全局

  • 使用电子邮件作为参数调用该函数

像这样的东西

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;
}

进一步阅读:

如何set全局变量。

为什么global变量不好。

答案 1 :(得分:1)

您的console.log在" emailCapture"之前运行事件被执行。这就是为什么它给你未定义,尝试执行此事件后你想做的一切。

 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();
});

答案 2 :(得分:0)

您需要首先初始化window.data_email然后变异。因为console.log将在初始化之前运行。