javascript函数的变量范围问题 [英] Variable scope issue with javascript function

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

问题描述

我正在尝试使用spin.js创建一个函数。该函数加载微调器,然后如果使用它参数再次调用它,则它会停止微调器。我无法使变量范围正确。因此,当我调用函数停止时,我在 submitSpinner 上得到一个未定义。

I am trying to create a function with spin.js. The function loads the spinner, then if it is called again with it argument, then it stops the spinner. I can't get the variable scope right. So when I call the function to stop, I get an undefined on the submitSpinner.

http://jsfiddle.net/atlchris/tQdZB/1/

function submitSpinner(stopSpinner) {
    var theSubmitSpinner;

    if (stopSpinner === true) {
        theSubmitSpinner.stop();

        $('#overlay').remove();
    }
    else {
        $('body').append('<div id="overlay"><div id="spinner"></div></div>');

        theSubmitSpinner = new Spinner({
            lines: 13,
            length: 15,
            width: 5,
            radius: 20,
            color: '#ffffff',
            speed: 1,
            trail: 60,
            shadow: false
        }).spin(document.getElementById("spinner"));
    }
}

submitSpinner();

$(function() {
    $('#overlay').on('click', function() {
        alert('click');
        submitSpinner(true);
    });
});​


推荐答案

为什么不从函数中返回 Spinner 对象,让调用者在它的时间调用.stop() ?读取更好,它不必用随机变量污染本地范围,也使 submitSpinner()更简单。

Why don't you return the Spinner object from the function, and let the caller call .stop() on it when its time? Reads better, and it doesn't have to pollute the local scope with random variables, also makes the submitSpinner() simpler.

function createSubmitSpinner() {

    $('body').append('<div id="overlay"><div id="spinner"></div></div>');

    return new Spinner({
        lines: 13,
        length: 15,
        width: 5,
        radius: 20,
        color: '#ffffff',
        speed: 1,
        trail: 60,
        shadow: false
    }).spin(document.getElementById("spinner"));
}


$(function() {
    var spinner = createSubmitSpinner();
    $('#overlay').on('click', function() {
        alert('click');
        spinner.stop();
    });
});

这篇关于javascript函数的变量范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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