javascript - 如何重构此 JavaScript 以删除 'with' 语句

标签 javascript refactoring with-statement

这是一个简单的时钟应用程序的 JS。 在 JS 中,不再使用“with”语句。 我希望帮助理解如何在删除“with”语句的使用的同时保留功能。谢谢。

function moveHands() {
  with (new Date()) {
    h = 30 * (getHours() % 12 + getMinutes() / 60); // 30 degrees for each hour
    m = 6 * (getMinutes()); // 6 degrees each minute
    s = 6 * (getSeconds()); 
    // now rotate the clock via changing css

    document.getElementById('hours').style.cssText = "-webkit-transform:rotate(" + h + "deg);";
    document.getElementById('minutes').style.cssText = "-webkit-transform:rotate(" + m + "deg);";
    document.getElementById('seconds').style.cssText = "-webkit-transform:rotate(" + s + "deg);";

    setTimeout(moveHands, 1000);
  }
}
window.onload = moveHands;

最佳答案

来自MDN with documentation :

Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.

基本上,这意味着您必须在使用对象之前将其分配给变量,这是非常标准的。 因此,在您的情况下,您的代码应如下所示:

function moveHands() {
  var date =  new Date();
    h = 30 * (date.getHours() % 12 + date.getMinutes() / 60); // 30 degrees for each hour
    m = 6 * (date.getMinutes()); // 6 degrees each minute
    s = 6 * (date.getSeconds()); 
    // now rotate the clock via changing css

    document.getElementById('hours').style.cssText = "-webkit-transform:rotate(" + h + "deg);";
    document.getElementById('minutes').style.cssText = "-webkit-transform:rotate(" + m + "deg);";
    document.getElementById('seconds').style.cssText = "-webkit-transform:rotate(" + s + "deg);";

    setTimeout(moveHands, 1000);

}

window.onload = moveHands;

关于javascript - 如何重构此 JavaScript 以删除 'with' 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43622517/

相关文章:

java - 从命令行在 Java 代码中进行更高级别的语义搜索和替换

vb.net - 从 VB.NET With block 退出

javascript - 如何使用自定义的 css 样式弹出选择菜单

javascript - 返回距离现在最近的时间的项目 JavaScript/Moment.js

javascript - 如何查看 React Router v6 中的查询字符串是否发生变化?

c# - 欧拉计划 : Problem 1 (Possible refactorings and run time optimizations)

c# - ReSharper 有哪些替代品?

甲骨文——带子句 => 合并? (语法错误,)

javascript - let block 语句和等价的 with 语句有什么区别?

javascript - 如何在 JavaScript 中循环浏览图片?