我已经尽力解决了这个问题,但是现在我陷入了困境,为什么第四个警报返回未定义?
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
没有影响。