闭包/范围JavaScript / jQuery [英] Closure/scope JavaScript/jQuery

查看:68
本文介绍了闭包/范围JavaScript / jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在
闭包(以避免污染全局命名空间)中分组一些现有的顶级函数,但我不是
让它工作。

$首先,所有的JS工作在我的匿名函数之外,但是一旦我把
它在匿名函数中,我得到一个错误crossfade不是
定义。有没有人看到任何完全明显的我是
丢失?



我不太明白为什么setInterval / crossfade工作之外的
匿名功能,但不在里面。 start()中的任何内容应该
能够看到在start()之外的vars /函数,它应该在由顶级匿名函数创建的闭包中保护

我不是正在尝试访问 crossfade()中的任何内容,我只是
尝试执行它。

 (function($){

//这里修改内部函数可以访问
//这里也使用一些jquery $

function crossfade(){
// body here
}

//其他函数

function start ){
// body here

cInterval = setInterval('crossfade()',5000);
}

})(jQuery);


解决方案

setInterval 方法会在窗口的范围内运行,所以交叉淡入淡出函数不存在。您必须创建一个匿名函数,以便创建一个包含对该函数的引用的闭包:

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


I'm trying to group some exisiting top-level functions inside a closure (to avoid polluting the global namespace) but I'm not quite getting it to work.

First, all the JS works outside my anonymous function, but once I put it in the anonymous function I get an error of "crossfade is not defined". Does anyone see anything completely obvious that I am missing?

I'm not quite getting why the the setInterval/crossfade works outside the anonymous function but not inside. Anything inside start() should be able to see vars/functions outside start() and it should all be protected in the closure created by the top-level anonymous function? I'm not trying to access anything within crossfade(), I'm just trying to execute it.

(function($) {

    //vars up here that internal functions can access
    //also using some jquery inside here, so using $

    function crossfade() {
        //body here
    }

    //other functions

    function start() {
        //body here

         cInterval = setInterval('crossfade()', 5000);
    } 

})(jQuery);

解决方案

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);

这篇关于闭包/范围JavaScript / jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆