我有这个代码 - 我只是想知道为什么在我将'var'添加到foo变量之后,它不起作用(它显示我foo未定义)...任何人都可以帮助解释这两个函数吗?谢谢!
window.onload = function() {
var test = foo().steps(2);
console.log(test);
}
(function() {
//if I remove var, then it prints out a function which is what I expected
var foo = function() {
var steps = 1;
function callMe(g) {
//do something else
console.log("hello" + g);
}
callMe.steps = function(x) {
//if no arguments then return the default value
if (!arguments.length) return steps;
console.log(arguments);
//otherwise assign the new value and attached the value to callMe
steps = x;
return callMe;
}
return callMe;
}
})();
答案 0 :(得分:1)
将var
添加到foo会使foo成为IIFE中的局部变量,因此您无法在外部访问它。