我正在尝试警报,但警报没有像我预期的那样工作,请看下面的行:
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 allowedfunction (){}
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/