具有默认参数的JavaScript函数 [英] JavaScript functions with default params

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

问题描述

我目前使用以下函数检查三个参数,看是否有任何传递过的方法,这是在没有发送任何参数的情况下设置默认值的最佳方法吗?

I currently use the following function which checks the three params to see if there are any passed through, is this the best way to do this whilst setting a default if no parameter has been sent?

function setupSlideshow(t, e, s) {
    e = e || '.slideshow';
    s = s || '> li';
    t = t || 70;
    $timeout(function() {
        $(e).cycle({
            swipe: true,
            slides: s,
            fx: 'scrollHorz',
            pager: '.cycle-pager',
            timeout: 0
        });
    }, t);
}

通过使用 setupSlideshow(70); ,这会将我的超时设置为 70 ms,但是在设置元素时,请使用 setupSlideshow('.new-幻灯片'); 不起作用.

By using setupSlideshow(70); this sets my timeout to 70ms but when it comes to setting the element then using setupSlideshow('.new-slideshow'); doesn't work.

setupSlideshow(70);
setupSlideshow('.new-slideshow');
setupSlideshow('.new-slideshow','.slide');

推荐答案

我认为您忘记了必须始终按顺序输入参数...这里的第一个参数是超时时间(以毫秒为单位),第二个参数是超时时间(以毫秒为单位)参数是幻灯片元素.如果您省略时间的完整性,则slideshow元素将是第一个参数,因此该函数会将其视为您的时间.

I think you have forgot that parameters always have to be entered in order... Here your first parameter is the time in milliseconds for your timeout, and the second parameter is the slideshow element. If you ommit your time completemy, the slideshow element will be the first parameter, so be treated as your time by the function.

jQuery用来解决此问题的一种方法是使用一个 option 参数.这包括传递一个对象供功能使用,如下所示:

One way jQuery uses to counter this is the use of one option parameter. This consist of passing an object for the function to use, this would look like that:

function setupSlideshow(options) {
    options = options || {};
    e = options.e || '.slideshow';
    s = options.s || '> li';
    t = options.t || 70;
    $timeout(function() {
        $(e).cycle({
            swipe: true,
            slides: s,
            fx: 'scrollHorz',
            pager: '.cycle-pager',
            timeout: 0
        });
    }, t);
}
setupSlideshow({t:70});
setupSlideshow({e:'.new-slideshow'});
setupSlideshow({e:'.new-slideshow',s:'.slide'});

使用这种技术对这种用法很有用,但是当可能有太多选项且没有充分记录时,也可能会成为问题的产生者,因此请保持其清洁和注释:)

Using this technique is useful for this kind of usage but may become a problem maker too when too many options are possible and not well documented so keep it clean and commented :)

这篇关于具有默认参数的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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