在IE9上的html页面中访问js内的全局函数

Erw*_*nGO 3 html javascript internet-explorer

我正在尝试访问我在main.js文件中声明的全局函数,并尝试在html页面中使用它:

<!DOCTYPE html>
<html>
  <head>

  </head>
  <body>
    <script src='main.js'></script>
    <script>
    (function(){
      window.myFunction();
    })();
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

还有我的main.js文件

(function(){
  window.myFunction = function(){
    alert(1);
  }
})();
Run Code Online (Sandbox Code Playgroud)

这适用于所有浏览器,但IE9并没有测试其他IE版本.你觉得我做错了什么?或者它与IE有什么关系?

VMc*_*tor 7

你应该在main.js中传递这样的window对象

(function(w){
  w.myFunction = function(){
    alert(1);
  }
})(window);
Run Code Online (Sandbox Code Playgroud)

"()"中的函数关键字后面的变量是函数内传递参数的别名,而封装函数末尾的"()"内的变量是传递的实变量.

演示:http://codepen.io/anon/pen/aOgZdB - 已在IE中尝试过.

我认为你可以直接将函数绑定到窗口的另一件事,你不需要把它放在封装函数中,如:

   window.myFunction=function(){
      alert(1);
   }
Run Code Online (Sandbox Code Playgroud)

在你的main.js中没有封装它.