在 $.ajax 之后为全局变量赋值并表现得像一个常量

问题描述

你好吗? 我想知道,有没有一种方法可以在 js 中声明一个不可变的变量(如 const 关键字),但是在可能是 ajax 请求或 fetch 之后才分配一次值?

我的问题很简单:我有 3 个 _id,当文档加载时我需要从我的服务器中检索它,我需要将它们存储在某个全局变量中。我需要这 3 个 _id 是不可变的,因为网站上所有下一个 ajax 请求都依赖于这些,我不能让别人更改这些变量中的值。

const 关键字是完美的,但我没有使用它们的范围,或者我无法在 ajax 请求之前声明变量。

解决方法吗?

const _id1 = null; // Correct,but this means nothing to me
const _id2; // Error: Missing initializer in const declaration
let _id_3 = null; // Formally correct,I can assign a new value to the variable
                  // but everybody can modify it from the console...

// What I need to do is
// 1) declare the variable
let magic_id;
// 2) do my ajax calls to my server
$.ajax({
    url,data,type,...,success(payload){
        // 3) Assign the value to my id
        let aPay = JSON.parse(payload);
        magic_id = aPay._id;
    }
});

// 4) If someone tries to assign a new value i need to prevent it
magic_id = new_value; // Uncaught TypeError: Assignment to constant variable.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)