我目前正在学习Javascript,请查看以下代码片段:
我在这里定义了3个立即调用的函数表达式。我的期望是当我 console.log(controller)返回 undefined 时。谁能解释一下,为什么 controller IIFE 能够返回一个Object而不是一个值?
var budgetController = (function() {
var x = 23;
var add = function(a) {
return x + a;
}
return {
publicTest: function(b) {
console.log(add(b));
}
}
})();
var UIController = (function() {
//Some UI based Code
})();
var controller = (function(budgetCtrl, UICtrl) {
var z = budgetCtrl.publicTest(5);
return z;
})(budgetController, UIController);
console.log(controller); // Should return the value of 'z' [My Confusion/Misconception lies here]
console.log(budgetController); // Returns a Object
答案 0 :(得分:0)
由于要将参数传递给publicTest,因此应返回值以将其存储在Z变量中
var budgetController = (function() {
var x = 23;
var add = function(a) {
return x + a;
};
return {
publicTest: function(b) {
console.log(add(b));
return add(b);
}
};
})();
var UIController = (function() {
//Some UI based Code
})();
var controller = (function(budgetCtrl, UICtrl) {
var z = budgetCtrl.publicTest(5);
return z;
})(budgetController, UIController);
console.log(controller); // Should return the value of 'z' [My Confusion/Misconception lies here]
console.log(budgetController);