【发布时间】:2013-11-12 12:28:07
【问题描述】:
以下两种声明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) -
实际上,这是去年回答的,如果您查看已接受答案下方的 cmets,我没有将分号更改为逗号。不确定您从哪里得到答案,因为我在问题中显示的代码有逗号 - 除非您只是复制了接受的答案
标签: javascript global-variables scope