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

时间:2017-04-25 23:20:41

标签: 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;

3 个答案:

答案 0 :(得分:2)

来自MDN with documentation

  

不推荐使用with,并且在ECMAScript 5 strict中禁止使用   模式。建议的替代方法是分配其对象   要访问临时变量的属性。

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

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;

答案 1 :(得分:2)

只需将日期分配给变量,然后在该变量上显式调用日期方法。

function moveHands() {
  var currentDate = new Date();

  h = 30 * (currentDate.getHours() % 12 + currentDate.getMinutes() / 60); // 30 degrees for each hour
  m = 6 * (currentDate.getMinutes()); // 6 degrees each minute
  s = 6 * (currentDate.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;

答案 2 :(得分:0)

我只想使用一个局部变量。

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;