javascript - 我应该如何理解 data.key 值始终未定义,但我可以使用 get set 或 change 等方法访问它

标签 javascript

我简化了我的问题。 在这段代码中

我尝试用谷歌搜索它,但我不知道如何调用它。

let data = () => {
    let key = undefined;
    let setKey = () => {
        key = Math.floor( Math.random() * 6);
    }
    let getKey = () => {
        return key;
    }
    let changeKey = (newKey) => {
        key = newKey;
    } 
    return {
        key,
        setKey,
        getKey, 
        changeKey
    }
}

let dataArray = []
for( let i = 0; i < 3; i++){
    dataArray.push(data())
}
dataArray.forEach( data => {console.log(data.key)})  // **undefined**
dataArray.forEach( data => {console.log(data.getKey())})  // **undefined**
dataArray.forEach( data => {data.setKey()})
dataArray.forEach( data => {console.log(data.getKey())}) // **rundom numbers**
dataArray.forEach( data => {console.log(data.key)})  // **undefined**

dataArray.length = 0;
for( let i = 0; i < 3; i++){
    dataArray.push(data())
}
dataArray.forEach( data => {console.log(data.getKey())})  // **uff -> undefined**

是的,所以我希望这很清楚我的理解问题在哪里。 可能是我对JS的一般理解有问题。 我希望你能帮助我。

最佳答案

整数未被引用,它立即用作值。在调用 return 语句的那一刻,您的 key 的值(未定义)被复制到您返回到 key 子对象中的对象(仍未定义)。

函数体内的key和返回的key是两个不同的对象。

我还添加了对象示例,因为对象值也被复制,但对象实际值是引用,而不是对象本身。

let data = () => {
    let key = undefined;
    let ourObject = {};
    let setKey = () => {
        key = Math.floor( Math.random() * 6);
        ourObject.key = key;
    }
    let getKey = () => {
        return key;
    }
    let getOurObject = () => { return ourObject; }
    let changeKey = (newKey) => {
        key = newKey;
    } 
    return {
        key,
        setKey,
        getKey, 
        changeKey,
        ourObject,
        getOurObject
    }
}

let ourData = data();
console.log('Should be undefined', ourData.key)
console.log('Still undefined', ourData.getKey())
ourData.setKey();
console.log('Now the value', ourData.getKey())
console.log('int is used by value directly, so it has the value it had when you executed data() and what was in return object at that time', ourData.key)
console.log('However objects are not used directly, their reference is copied and therefore through same reference you can get to the object', ourData.ourObject)
ourData.ourObject = null;
console.log('Still the ourObject variable itself is different than the one returned', ourData.ourObject)
console.log('This is reason the variable was nulled, but object still exist', ourData.getOurObject())

关于javascript - 我应该如何理解 data.key 值始终未定义,但我可以使用 get set 或 change 等方法访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55491656/

相关文章:

javascript - 移动网页的 Twitter 身份验证?

javascript - 检查服务器端更新的侵入性最小的方法是什么

javascript - Vue 和对任何元素的涟漪效应

javascript - 如何拦截类实例中的所有错误?

javascript - 为一个点添加事件监听器

javascript - json 对象 javascript 困惑

在数组上使用时 Javascript/JQuery join() 方法错误

javascript - 搜索不可变的 JS Map

javascript - 为什么 "window"对象有这么多嵌套的 "window"对象?

javascript - 无法获取所选选择标签的标签文本