最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript window is undefined - Stack Overflow

programmeradmin2浏览0评论

Here is some of my javascript:

(function(window) {
  window.file = {};
  file.i = 0;
  
  for(;;) {
     if(file.i++ >= 10) break;
     document.body.appendChild(document.createTextNode(file.i))
  } 
  
 
}) ();

Here is some of my javascript:

(function(window) {
  window.file = {};
  file.i = 0;
  
  for(;;) {
     if(file.i++ >= 10) break;
     document.body.appendChild(document.createTextNode(file.i))
  } 
  
 
}) ();

Why is window undefined?

Share Improve this question edited Jan 21, 2019 at 19:58 chuck asked Jan 21, 2019 at 19:37 chuckchuck 331 silver badge5 bronze badges 2
  • window is supposed to be the global object. You probably wouldn't need to pass it to function. Also note that document is a property of window. – frogatto Commented Jan 21, 2019 at 19:42
  • I do that so it is more readable, and sometimes i like to pass a different object rather than window. – chuck Commented Jan 21, 2019 at 19:45
Add a ment  | 

2 Answers 2

Reset to default 7

You need to call the anonymous function with window as the first argument:

(function(window) {
  window.file = {};
  file.i = 0;
  
  for(;;) {
     if(file.i++ >= 10) break;
     document.body.appendChild(document.createTextNode(file.i))
  } 
}) (window);

Since you provided nothing, window inside of your function's scope was considered undefined.

Try

(function(window) {
  window.file = {};
  file.i = 0;
  
  for(;;) {
     if(file.i++ >= 10) break;
     document.body.appendChild(document.createTextNode(file.i))
  } 
  
 
})(window);

发布评论

评论列表(0)

  1. 暂无评论