gpt4 book ai didi

JavaScript 变量似乎被视为函数

转载 作者:行者123 更新时间:2023-11-28 15:37:25 27 4
gpt4 key购买 nike

我正在开发一些位于 SharePoint 页面上的 JavaScript。 SharePoint 提供了一个全局函数 getCurrentCtx()。不幸的是,此功能仅在某些页面上可用。我的 JavaScript 需要测试一下这个函数是否存在。

简单吧?

if(getCurrentCtx) {
//Code here
}

没那么快:

Uncaught ReferenceError: getCurrentCtx is not defined

什么鬼?如果未定义,则应为 undefined,这是错误的,因此应跳过 if 语句。

console.log(getCurrentCtx)

Uncaught ReferenceError: getCurrentCtx is not defined

据我所知,当您尝试调用不存在的函数时,会发生 Uncaught ReferenceError 异常。那么为什么当我只是尝试检索变量的值时却得到它呢?

谢谢

YM

最佳答案

As far as I know, the uncaught referencerror exception occurs when you try to call a function that doesn't exist.

不正确。

如果您尝试读取不存在的任何变量(或更一般的绑定(bind))的值(例如,没有 var getCurrentCtx 任何地方),然后 JS 抛出引用错误。

Relevant part in the specification

异常:typeof getCurrentCtx would return "undefined" ,因为它在读取变量(引用)之前测试变量(引用)是否可解析(存在)。

关于JavaScript 变量似乎被视为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25149932/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com