这两种声明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