Oneliner:为什么这个收益未定义不是一个函数

Oneliner: Why does this yield undefined is not a function?

本文关键字:函数 一个 未定义 为什么 收益 Oneliner      更新时间:2023-09-26

为什么以下行有时会在 chrome 开发控制台中产生消息"未定义不是函数":

(callbackOrUndefined || function() {})();

这个想法是执行回调,如果它是真实的,即一个函数,否则执行空函数。

我不得不用:

if (callbackOrUndefined !== undefined) callbackOrUndefined();

编辑:我想我不够清楚。它有时似乎将块评估为 undefined();我不明白如何以及为什么。

那是因为callbackOrUndefined有一个假值,然后选择了 null 函数,调用时,它会返回 undefined

请注意,即使callbackOrUndefined没有返回定义的值,您也可能得到undefined...

我假设callbackOrUndefined没有定义。所以它的价值被认为是虚假的。然后,OR计算空函数。空函数不返回任何内容。Chrome 开发控制台始终会打印您执行的任何代码的最后一个返回值。在这种情况下,这是未定义的。

顺便说一句,它不是总是返回undefined.为了不返回undefinedcallbackOrUndefined需要有一些真实的值。