未捕获的ReferenceError:getDetails未定义

Uncaught ReferenceError: getDetails is not defined

本文关键字:getDetails 未定义 ReferenceError      更新时间:2023-10-23

我正在尝试执行以下JavaScript代码,但遇到了错误。

var services = [{place_id:'okkkkkk'}];
var delay = 100;
var nextAddress = 0;
function theNext() {
  if (nextAddress < services.length) {
    setTimeout('getDetails("' + services[nextAddress].place_id + '", theNext)', delay);
    nextAddress++;
  } else {
  }
}

function getDetails(address, next) {
  alert('ok');
}

theNext();

错误:

VM687:1未捕获引用错误:未定义getDetails

函数已经定义,我不确定是什么导致了问题:

https://jsfiddle.net/qmnaykqw/

当您将字符串传递给setTimeout时,它将在全局范围内进行求值。由于getDetails是在另一个名为onload的函数(至少在您的JSFiddle链接上)中定义的,因此在计算字符串时它超出了作用域。

您需要将一个函数传递给setTimeout。这将创建一个闭包并保留范围。

function delayed_function() {
    getDetails(services[nextAddress].place_id, theNext);
}
setTimeout(delayed_function, delay);