Closure/scope JavaScript/jQuery

狂风中的少年 提交于 2019-12-03 15:29:54

The setInterval method will be run in the scope of the window, so the crossfade function doesn't exist there. You have to make an anonymous function so that a closure is created that contains a reference to the function:

cInterval = window.setInterval(function() { crossfade(); }, 5000);

Using setInterval('crossfade()', 5000); doesn't create a closure - it creates a string to be eval()d. You should use a function instead:

setInterval(function() { crossfade(); }, 5000);

When setInterval is passed a string, the string is evaluated in global scope. That explains why crossfade is not visible when setInterval fires.

setInterval can also be passed a function reference:

setInterval(crossfade, 5000);

in which case your code will work as expected, since crossfade is visible at the point where you call setInterval.

To avoid polluting the global scope, you can do a few things:

  • Extend jQuery, since you're already using jQuery. (Use jQuery as a namespace.)
  • Create a single object to hold your methods. (Create your own namespace.)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!