我已經盡力解決了這個問題,現在我被卡住了,爲什麼第四次提醒返回undefined?在JavaScript中設置對象值
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
我以爲functionCallFromOutside只包含函數定義,它會稍後執行「test.functionCallFromOutside()」?我的思想在哪裏錯了? – Lee
這不是你思考錯誤的地方。它*在你調用'test.functionCallFromOutside()'時執行。問題是你期望當函數設置_setInFunctionCalledFromOutside =「爲什麼這會回到未定義的狀態?」它還會*更新'setInFunctionCalledFromOutside'屬性。 – Jacob
啊,我看到我錯了什麼地方,我沒想到它也會更新值,但我感覺setInFunctionCalledFromOutside更像是一個C#getter屬性...將其更改爲一個函數,然後我稱它爲一個吸氣劑給出了預期的結果。謝謝你的幫助! – Lee