当我在闭包中将 js 逻辑编写为单个 js 文件时,一切正常,如下所示:
(function(win){ //main logic here win.expose1 = .... win.expose2 = .... })(window)
但是当我尝试在同一个 js 文件中的闭包之前插入一个日志记录替代函数时,
window.Glog = function(msg){ console.log(msg) } // this was added before the main closure. (function(win){ //the former closure that contains the main javascript logic; })(window)
它抱怨有一个TypeError:
Uncaught TypeError: (intermediate value)(...) is not a function
我做错了什么?
该错误是第三行缺少分号的结果:
window.Glog = function(msg) { console.log(msg); }; // <--- Add this semicolon (function(win) { // ... })(window);
ECMAScript 规范对自动插入分号有特定的规则,但是在这种情况下不会自动插入分号,因为从下一行开始的带括号的表达式可以解释为函数调用的参数列表。
这意味着如果没有该分号,匿名window.Glog函数将被调用,并以函数作为msg参数,然后(window)尝试调用返回的任何内容。
window.Glog
msg
(window)
这就是代码的解释方式:
window.Glog = function(msg) { console.log(msg); }(function(win) { // ... })(window);