Javascript函数参数必须是一个字符串?

Ryd*_*der 3 javascript

我是javascript的新手,所以我不确定为什么它会像这样.

我有一个时钟功能:

function updateClock()
{
var currentTime = new Date();

var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
var currentMilliseconds = currentTime.getMilliseconds();

// Pad the minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

// Choose either "AM" or "PM" as appropriate
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

// Convert the hours component to 12-hour format if needed
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

// Convert an hours component of "0" to "12"
currentHours = ( currentHours == 0 ) ? 12 : currentHours;

// Update the time display
document.getElementById("clock").innerHTML = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
}
Run Code Online (Sandbox Code Playgroud)

这是一个单独的clock.js文件.我将该文件包含在头部.

我把它放在clock div:

<script type="text/javascript">
setInterval("updateClock()", 1000);
</script>
Run Code Online (Sandbox Code Playgroud)

它有效.但是,如果我改变它setInterval(updateClock(), 1000);,它将无法正常工作.我花了一段时间试图弄清楚为什么函数只执行一次,直到我发现我需要在函数调用周围加上引号.

来自不同语言的背景,我不知道为什么你需要在它周围加上引号?看起来我正在将字符串传递"updateClock()"给函数而不是另一个函数.我看到其他人的代码,他们只是将整个函数定义为参数,如setInterval(function(){ ... }, 1000).

Mic*_*ski 8

setInterval() 作为第一个参数

  1. 要评估的一串代码('updateClock()') - 这不是首选用途,因为它依赖于它eval().该字符串被评估为JavaScript代码.
  2. 指向函数的指针(updateClock) - 注意缺少parens.在JavaScript中,可以通过使用其名称来引用已定义的函数,而不是调用().指针也可以是一个匿名函数setInterval(function(){stuff...}, time),它实际上与对已定义函数的引用相同 - 都指向函数在内存中的位置,无论它是否具有名称.

所以在你的情况下,首选用法是:

<script type="text/javascript">
  setInterval(updateClock, 1000);
</script>
Run Code Online (Sandbox Code Playgroud)

它的堂兄同样如此setTimeout().