javascript - JavaScript 中警报函数的意外行为

标签 javascript function alert first-class

我正在尝试警报,但警报没有像我预期的那样工作,请看下面的行:

var tobealerted = function(){return 'worked!'};

现在当我发出警报时:

alert(tobealerted());

这会工作得很好!现在

alert(tobealerted);

在此我删除了括号。现在它警告 function(){return "worked"} not worked! 现在我认为这可能是 javascript 的一个功能,它会提醒任何文本而不用引号引起来,然后我写道:

alert(worked!)

但是谷歌控制台抛出异常 worked! is undefined ,所以我的想法是错误的。然后我又写了这个

alert(function(){})

你知道它提醒了什么function(){}!然后我认为警报只会允许在不带引号的情况下提醒此类声明。然后又写道:

alert(if(){}) //if is not defined
alert(for(){}) //for is not defined
alert(while(){}) //while is not define

但是这些不起作用,我搜索并找到了一些东西,从我的搜索中我发现了这个

functions are first class object

根据维基百科:

In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. Specifically, this means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures

所以我的问题是

why did alert function only allowed function (){} to be alerted but not others

如果您认为这是因为该函数是一等对象,那么我不这么认为,因为 我没有将此函数(最后一个)分配给任何变量,也没有在 alert(function(){}) 中返回任何内容

我很好奇,也很困惑! 谢谢!

最佳答案

你自己已经给出了答案。函数是对象并且as such have toString() functions 。您给出的其他示例是语句,而不是对象

正如其他人所指出的,window.alert()只显示String对象并触发任何其他类型对象的toString()函数。它期望您提供给它的任何内容都是对象或对象的引用。
这就是当你试图提醒这些陈述时发生的事情;它假定 if 等是变量名称,但找不到该名称的任何引用。

关于javascript - JavaScript 中警报函数的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22661863/

相关文章:

PHP 警报消息

javascript - 科尼 : import image from phone to app

JavaScript : Alert Box dismissed when tabs switched

java - 如何使用 Java 在 Appium 中处理 native iOS 警报

javascript - JavaScript 包含图像时出错

c - 在 C 中将多维数组作为函数参数传递

c++ - 通过指针调用函数

php - 在 HTML 页面中编写 PHP 代码的首选方法?

javascript - Opencart Javascript 弹出必需选项警报

javascript - 多个帧在同一个浏览器线程中执行?