编程语言
首页 > 编程语言> > 声明JavaScript变量

声明JavaScript变量

作者:互联网

以下两种声明javascript变量的方式有何区别?

版本1

var shadowBox = $(this);
var startInfo = shadowBox.children('.start-info');
var originalHeight = startInfo.height();

版本2

var shadowBox = $(this),
    startInfo = shadowBox.children('.start-info'),
    originalHeight = startInfo.height();

我之所以这么问是因为我在jquery插件中使用了第二个版本:

(function ($) {
    $.fn.setUpShadowBox = function (options) {
        options = $.extend({
            boxSpeed: 750,
            boxWidth: 998,
            boxPosition: -40,
            heightSpeed: 500,
            scrollSpeed: 750
        }, options);

        return $(this).each(function () {
            var shadowBox = $(this),
                startInfo = shadowBox.children('.start-info'),
                originalHeight = startInfo.height();

            //rest of plugin code
        });
    };
});

但是,当我在类选择器上使用它时,它不得不遍历多次,它会将变量视为全局变量,并且仅使用设置的最后一个originalHeight.一旦将其更改为声明变量的第一个版本,我的插件即可按预期工作,并且变量保持在其范围之内.

为什么是这样?

解决方法:

您是否错过了第一行的逗号?

如果您这样做:

var shadowBox = $(this)
    startInfo = innerContainer.children('.start-info');

代替这个:

var shadowBox = $(this),
    startInfo = innerContainer.children('.start-info');

startInfo将成为全局变量.

尝试将它们全部放在同一行上,看看会发生什么.

标签:scope,global-variables,javascript
来源: https://codeday.me/bug/20191122/2060325.html