gpt4 book ai didi

javascript - 在 JavaScript 中设置对象值

转载 作者:行者123 更新时间:2023-11-30 10:37:10 25 4
gpt4 key购买 nike

我已经尽力解决了这个问题,现在我卡住了,为什么第四个警报返回未定义?

function buttonClick()
{
var myTest = function()
{
var _setDirectlyInside = "So far so good...";
var _setInFunctionCalledInside;
var _setInFunctionCalledFromOutside;

(function(){
_setInFunctionCalledInside = "This would indicate scope isn't the problem?";
})();

return {
basic : "Easy stuff",
setDirectlyInside : _setDirectlyInside,
setInFunctionCalledInside : _setInFunctionCalledInside,
functionCallFromOutside : function(){
_setInFunctionCalledFromOutside = "Why does this come back as undefined?";
},
setInFunctionCalledFromOutside : _setInFunctionCalledFromOutside
}
};

var test = myTest();

alert(test.basic); // Returns "Easy stuff"
alert(test.setDirectlyInside); // Returns "So far so good..."
alert(test.setInFunctionCalledInside); // Returns "This would indicate scope isn't the problem?"

test.functionCallFromOutside();
alert(test.setInFunctionCalledFromOutside); // Broken, returns undefined
}

解决方案:

setInFunctionCalledFromOutside : _setInFunctionCalledFromOutside, // Won't work
setInFunctionCalledFromOutsideGetter : function(){
return _setInFunctionCalledFromOutside; // Will work
}

...

alert(test.setInFunctionCalledFromOutside); // Broken, returns undefined
alert(test.setInFunctionCalledFromOutsideGetter()); // Now works

最佳答案

这个:

return {
basic : "Easy stuff",
setDirectlyInside : _setDirectlyInside,
setInFunctionCalledInside : _setInFunctionCalledInside,
functionCallFromOutside : function(){
_setInFunctionCalledFromOutside = "Why does this come back as undefined?";
},
setInFunctionCalledFromOutside : _setInFunctionCalledFromOutside
}

...不会导致 setInFunctionCalledFromOutside 始终返回与 _setInFunctionCalledFromOutside 相同的值。相反,_setInFunctionCalledFromOutside 将在 return 语句执行时计算,其值将放在 setInFunctionCalledFromOutside 中。因此,functionCallFromOutside() 不会影响 setInFunctionCalledFromOutside

关于javascript - 在 JavaScript 中设置对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com