测试 Javascript 中未定义的函数

发布于 2024-11-08 06:01:04 字数 344 浏览 3 评论 0原文

因此 Safari 一直因为一个特定错误而对我大喊大叫。

我正在尝试使用 Google Maps API 并调用 map.getCenter();。但有时,这种情况会发生在地图完全加载之前。

因此,在我的函数中,我测试了一个 undefined 调用,如下所示:

if (map.getCenter() != undefined)

但这仍然会出错,因为我猜它甚至不喜欢只是为了测试结果是否 undefined 而进行调用是否?

我可以在这里得到一些帮助吗?

谢谢!

So Safari keeps yelling at me for one specific error.

I'm trying to use Google Maps API and call map.getCenter();. However sometimes, this happens before the map has been fully loaded.

So instead in my function I test for an undefined call like this:

if (map.getCenter() != undefined)

But that still errors out because I guess it doesn't even like making the call just to test the if the result is undefined or not?

Can I get some help here?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

生寂 2024-11-15 06:01:04

我实际上更喜欢类似的东西。

if(typeof myfunc == 'function') { 
    myfunc(); 
}

仅仅因为某些东西不是未定义的,并不意味着它就是一个函数。

I actually prefer something along these lines.

if(typeof myfunc == 'function') { 
    myfunc(); 
}

Just because something isn't undefined doesn't make it a function.

只怪假的太真实 2024-11-15 06:01:04
if (typeof map !== 'undefined' && map.getCenter) {
   // code for both map and map.getCenter exists
} else {
  // if they dont exist
}

这是检查函数是否存在的正确方法。调用函数来测试其存在将导致错误。

更新:代码片段已更新。

if (typeof map !== 'undefined' && map.getCenter) {
   // code for both map and map.getCenter exists
} else {
  // if they dont exist
}

This is the right way to check for existence of a function.. Calling the function to test its existence will result in an error.

UPDATE: Snippet updated.

樱花坊 2024-11-15 06:01:04

从技术上讲,您应该测试 map 是否未定义,而不是 map.getCenter()。您无法对未定义的引用调用函数。

不过,Google 自己的教程建议您调用 JavaScript 来访问body.onload 处理程序中的 API,以便在加载所有远程 .js 文件之前不会尝试引用任何内容 - 您正在这样做吗?这将永久解决问题,而不是在加载 API 之前执行 JavaScript 时彻底失败。

Technically you should be testing if map is undefined, not map.getCenter(). You can't call a function on an undefined reference.

However, Google's own tutorial suggests that you invoke your JavaScript that accesses the API in a body.onload handler, so that you do not attempt to reference anything until all of the remote .js files are loaded - are you doing this? This would solve the problem permanently, rather than failing cleanly when your JavaScript executes prior to loading the API.

安稳善良 2024-11-15 06:01:04
if (typeof map.getCenter !== 'undefined')

不会抛出错误。

因此,更好的是 if (typeof map.getCenter === 'function') map.getCenter();

if (typeof map.getCenter !== 'undefined')

Won't throw an error.

So, better yet, if (typeof map.getCenter === 'function') map.getCenter();

抚你发端 2024-11-15 06:01:04

我最近养成了使用 typeof 运算符来测试事物和类型的习惯。它将类型作为字符串返回,我认为这可以避免一些响应类型混淆。

if( typeof map.getCenter != 'undefined') ...

我不确定它是否更正确,但我发现这个过程取得了很好的结果。

I have been in the habit recently of using the typeof operator to test for things and types. It returns the type as a string which I think avoids some response type confusion.

if( typeof map.getCenter != 'undefined') ...

I'm not sure if it's more correct, but I find good results with this process.

计㈡愣 2024-11-15 06:01:04

现在有一个可选的链接运算符可以完成此任务。

可选链接 (?.) 运算符访问对象的属性或调用函数。如果使用此运算符访问的对象或调用的函数未定义或为 null,则表达式会短路并计算为未定义,而不是抛出错误。

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// Expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// Expected output: undefined

https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

There is now an optional chaining operator that does exactly this.

The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// Expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// Expected output: undefined

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

故事还在继续 2024-11-15 06:01:04

您应该测试 map 是否未定义。在当前检查中,您仍在尝试执行函数调用。

You should be testing whether map is undefined. In your current check your are still trying to execute the function call.

扭转时空 2024-11-15 06:01:04

假设 map.getCenter() 始终是一个函数,则只需使用此检查就足够了:

if (map.getCenter) {
      var x = map.getCenter();
}

Assuming that map.getCenter() is always a function, it's sufficient to just use this check:

if (map.getCenter) {
      var x = map.getCenter();
}
清眉祭 2024-11-15 06:01:04

对我来说有效的解决方案是try and catch

const stopPropagation = (e) => {
    try {
        e.stopPropagation();
    } catch (err) {
        console.log("error with stopPropagation: " + err.error);
    }
}

const triggerClick = (e) => {
    stopPropagation(e);
};

The worked solution for me is try and catch,

const stopPropagation = (e) => {
    try {
        e.stopPropagation();
    } catch (err) {
        console.log("error with stopPropagation: " + err.error);
    }
}

const triggerClick = (e) => {
    stopPropagation(e);
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文