变量超出作用域

4

我正在制作响应式背景视频。我有这段代码。

<video id="bgvideo" />

function scaleVideo() {

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();

    var videoNativeWidth = $('video#bgvideo')[0].videoWidth;
    var videoNativeHeight = $('video#bgvideo')[0].videoHeight;


    var heightScaleFactor = windowHeight / videoNativeHeight;
    var widthScaleFactor = windowWidth / videoNativeWidth;


    if (widthScaleFactor >= heightScaleFactor) {
        var scale = widthScaleFactor;
    } else {
        var scale = heightScaleFactor;
    }

    var scaledVideoHeight = videoNativeHeight * scale;
    var scaledVideoWidth  = videoNativeWidth * scale;

    $('video#bgvideo').height(scaledVideoHeight);
    $('video#bgvideo').width(scaledVideoWidth);
}

我正在使用grunt编译我的代码等内容。Grunt的Jshint插件提示我正在使用不在作用域内的"scale",但我无法理解原因。有什么建议吗? error

1
我认为JSHint的作用域分析没有考虑块。 - Felix Kling
2个回答

5

如果你想在else语句之外使用它,那么就不应该在else语句内部写var scale = heightScaleFactor;

if语句之外初始化scale

 var scale;
 if (widthScaleFactor >= heightScaleFactor) {
     scale = widthScaleFactor;
 } else {
     scale = heightScaleFactor;
 }

"你不能在else循环内部编写var scale = heightScaleFactor;。" 当然可以。 - Felix Kling

2
尝试使用这个替代方案:
function scaleVideo() {
    var scale; //this is the change

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();

    var videoNativeWidth = $('video#bgvideo')[0].videoWidth;
    var videoNativeHeight = $('video#bgvideo')[0].videoHeight;


    var heightScaleFactor = windowHeight / videoNativeHeight;
    var widthScaleFactor = windowWidth / videoNativeWidth;


    if (widthScaleFactor >= heightScaleFactor) {
        scale = widthScaleFactor; //simply modify the value here
    } else {
        scale = heightScaleFactor;
    }

    var scaledVideoHeight = videoNativeHeight * scale;
    var scaledVideoWidth  = videoNativeWidth * scale;

    $('video#bgvideo').height(scaledVideoHeight);
    $('video#bgvideo').width(scaledVideoWidth);
}

“var scale” 只在 if..else.. 的范围内定义。然而,if/else 语句并不会创建作用域。 - Felix Kling

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