我正在尝试运行以下代码。它向我抛出了一个类型错误:hello不是Logger.log(hello(((的第二次调用中的函数
这里有两个功能:
function hello() {
return hello = 'hello';
}
function testHello() {
Logger.log(hello());
Logger.log(hello());
}
如果您能解释为什么会发生这种情况以及解决方法,我们将不胜感激。
我想当我看到您的脚本时,在您的脚本中,会运行以下流。
- 在第一次运行
testHello()
的Logger.log(hello());
时,hello()
作为函数运行,并返回字符串值的hello
。此时,hello
被分配有一个字符串值。由此,hello
从函数变为字符串作为全局 - 在第二次运行
Logger.log(hello());
时,hello
为字符串。由此,出现类似TypeError: hello is not a function
的错误。- 我认为这就是你问题的原因
例如,当脚本中使用typeof hello
时,您可以看到类型的更改。示例脚本如下。
function hello() {
return hello = 'hello';
}
function testHello() {
Logger.log(typeof hello);
Logger.log(hello());
Logger.log(typeof hello);
Logger.log(hello());
}
运行此脚本时,您可以在日志中看到以下值。
function
hello
string
TypeError: hello is not a function <--- An error occurs here.
如果你想避免这个错误,下面的修改怎么样?
function hello() {
var hello = 'hello'; // or let or const instead of var
return hello;
}
function testHello() {
Logger.log(typeof hello);
Logger.log(hello());
Logger.log(typeof hello);
Logger.log(hello());
}
在这种情况下,您可以在日志中看到以下值。
function
hello
function
hello