这是一个简单的时钟应用程序的 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;
最佳答案
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/