用if(cond)esle if(sameCond)两次检查同一条件有什么意义

What is the meaning of checking the same condition two times with if(cond) esle if(sameCond)?

本文关键字:if 条件 一条 什么 esle cond sameCond 两次 检查      更新时间:2023-09-26

我正在阅读一个名为Panda.js的游戏引擎。核心中有一种方法可以检查浏览器是否支持全屏,但我不理解这个代码:

if (this.system.canvas.requestFullscreen)
    this.system.canvas.requestFullscreen();
else if (this.system.canvas.requestFullScreen)
    this.system.canvas.requestFullScreen();

如果你仔细观察,你会发现它们不是相同的条件。这两种方法不同,因为一种是资本,另一种不是。我猜开发人员做了一个小写来表示它不是全屏的,资本是全屏的。不管怎样,情况都不一样。

if (this.system.canvas.requestFullscreen)
    this.system.canvas.requestFullscreen();
else if (this.system.canvas.requestFullScreen)
    this.system.canvas.requestFullScreen();`

屏幕中的S发生变化。

通常,在ifelse中不会使用完全相同的条件。除非评估条件会改变后续调用的结果——可以说是一个糟糕的设计选择——否则else块永远不会被执行,并且当条件评估为false时,它将被不必要地测试两次。

也就是说,@Brendan是正确的:这个代码没有相同的条件。详见他的回答。