Javascript变量不更新/保存

时间:2017-11-26 08:59:25

标签: javascript variables

我有一个我需要多个函数的字符串。因此,我想将其保存在变量中。
但是当我尝试在函数内部分配它时,它不会更新变量。

var auth_code = "na";
function safeAuthCode(authcode){
  auth_code = authcode;
  console.log(auth_code);
}

auth_code”在控制台上打印得很好,但是当我稍后尝试使用它时它只包含“na”。
不确定我做错了什么:/

编辑:

这是调用safeAuthCode的函数:

function auth(){
  chrome.identity.launchWebAuthFlow({
    "url": "https://accounts.spotify.com/authorize?client_id="+client_id+
    "&redirect_uri="+ encodeURIComponent(redirectUri) +
    "&response_type=code"+
    "&scope=" + encodeURIComponent(scopes),
    "interactive": true
  },
  function(redirect_url) {
    var url = new URL(redirect_url);
    var code = url.searchParams.get("code");
    safeAuthCode(code);
  });
}

2 个答案:

答案 0 :(得分:0)

我假设您遇到的问题是因为全局变量要么在代码的不同部分被覆盖,要么因为某个时间点的代码重新加载,并且初始值被重置。 / p>

要保存此类身份验证代码,您可以使用浏览器的sessionStorage对象。

为了确保你只有1个这样的对象,你可以使用const关键字来定义变量(如果该变量的另一个定义将在以后发生,你应该抛出一个错误)< / p>

const authorisationSettings = {
  get code() {
    return sessionStorage.getItem('authorisationCode') || 'na';
  },
  set code(value) {
    return sessionStorage.setItem('authorisationCode');
  }
};

function saveAuthorisationCode( code ) {
  authorisationSettings.code = code;
}

saveAuthorisationCode( 'test' );
console.log( authorisationSettings.code );

此代码段不适用于stackoverflow,因此您可以找到jsfiddle here

答案 1 :(得分:-1)

这是因为你的函数执行时,在该函数的词汇环境中已经存在authcode变量而你试图设置这个而不是全局authcode

您需要更改全局变量的名称或功能的参数...