为什么函数中的变量覆盖全局变量?

时间:2017-10-25 13:22:37

标签: javascript

我在函数外部定义了一个变量myData,我尝试将从axios获得的数据分配给变量myData,但是失败了。变量shareData在函数内部具有正确的值 - response.data - 但在退出函数时,它的值变为原始值。

它必须是局部变量覆盖外部变量,那么如何避免这种情况并让外部变量得到response.data值?

var shareData = 'OUTSIDE THE FUNCTION'

axios({
    method: 'get',
    url: '/api/usershare', //API
    responseType: 'json',
  })
  .then(function(response) {
    shareData = response.data
    console.log(shareData) //output the reponse.data correctly
  })
console.log(shareData) //output OUTSIDE TEH FUNCTION, which is the orignal value of myData

0 个答案:

没有答案