声明javascript变量

3
这两种声明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) 的末尾。 - NAZIK
实际上,这个问题去年已经回答过了。如果你看一下被接受的答案下面的评论,你会发现我没有把分号改成逗号。不确定你从哪里得到了你的答案,因为我在问题中展示的代码是有逗号的 - 除非你只是复制了被接受的答案。 - Pete
2个回答

3

你第一行有没有漏掉逗号?

如果你这样做:

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

请避免这样做:

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

startInfo 将成为全局变量。

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


出于好奇,为什么缺少逗号会使startInfo变成全局的? - Rémi Benoit
由于自动分号插入,请参见此链接:https://dev59.com/JnE85IYBdhLWcg3wSxkv - pax162
啊,类似的错误 - 当我添加一个新变量时,我忘记把分号改成逗号了!等我修改后会接受的。 - Pete
这样声明的变量 function() {var local; global = 2;} 会是全局的吗?不太明白为什么。 - Rémi Benoit
在学习的过程中有所收获!我越深入了解JS,就越发现其中更多奇怪的事情。 - Rémi Benoit

0
请看一下声明JavaScript变量,这将非常有用。你的问题在于var shadowBox = $(this),你漏了一个逗号。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接