Javascript函数传递
我有以下问题。我需要将hello函数传递给name,然后他们调用它。但是我得到了错误,hello不是一个函数Javascript函数传递,javascript,html,Javascript,Html,我有以下问题。我需要将hello函数传递给name,然后他们调用它。但是我得到了错误,hello不是一个函数 <html> <head> <title>D</title> <script type="text/javascript"> hello = function(){ alert("hello! I'm called") ;
<html>
<head>
<title>D</title>
<script type="text/javascript">
hello = function(){
alert("hello! I'm called") ;
}
</script>
</head>
<body>
<script type="text/javascript">
name = function( hello ) {
hello() ;
}
name();
</script>
</body>
</html>
D
hello=函数(){
警惕(“你好!我有电话”);
}
name=函数(hello){
你好;
}
名称();
在name
内部,hello
将引用参数hello
。当您在不传递任何参数的情况下调用函数时,hello
是undefined
或者将函数作为参数传递
name(hello);
或者省略参数说明,以便hello
将引用全局变量:
name = function() {
hello();
};
您应该避免使用全局变量,以便它们不会与window
属性或其他库冲突。可以将对象用作命名空间:
var myNameSpace = {};
myNameSpace.hello = function...
myNameSpace.name = function...
您正在name()
中定义一个名为hello
的参数,但您在调用name()
时没有参数,因此hello
在name()
的上下文中未定义。调用name()
时传递参数,或完全删除参数:
name = function (hello) {
hello();
}
name(hello);
或
我会把它完全改成这样:
function hello(){
alert("hello! I'm called");
}
function name(hello) {
hello() ;
}
name(hello);
不需要像现在这样将函数分配给变量
正如其他人所说,主要问题是没有向name函数传递任何内容。代码有两个问题
<html>
<head>
<title>D</title>
<script type="text/javascript">
hello = function(){
alert("hello! I'm called") ;
}
</script>
</head>
<body>
<script type="text/javascript">
name = function( hello ) {
hello() ;
}
name();
</script>
</body>
</html>
不能声明已存在于窗口
类中的变量
名称
您的名称函数
包含一个由hello
函数命名的参数。为此,您需要传递一个函数委托才能实现这一点
请看下面的完整代码:
<html>
<head>
<title>D</title>
<script type="text/javascript">
var hello = function(){
alert("hello! I'm called") ;
}
</script>
</head>
<body>
<script type="text/javascript">
var nameFunc = function( helloDelegate ) {
helloDelegate() ;
}
nameFunc(hello);
</script>
</body>
</html>
D
var hello=function(){
警惕(“你好!我有电话”);
}
var nameFunc=函数(helloDelegate){
helloDelegate();
}
nameFunc(你好);
Dewsworld,学习如何调试javascript。它将帮助你调查问题并自己找到解决方案。在某些浏览器中,调试器是内置的,在另一些浏览器中,您必须下载调试器。但这并不重要
一旦您开始一步一步地执行脚本,您将看到它的所有变量的当前状态,这将比给出您遇到的问题的原因更清楚、更有效
另外,请阅读JavaScript最终指南,即最新版。至少试着在书中找到解决办法和原因。因为在这里,您通常只能得到简短的解决方案,而无法深入了解JavaScript引擎的工作原理。您可以使用名称函数定义中使用的参数“hello”隐藏hello函数。调用name()时,不传递函数。叫名字作为名字(你好);也不要隐藏像这样的全球名称this@Alexandr行动!我的错误。但在这种情况下,Firefox运行良好,chrome不行。你不能简单地做function(){hello();}
@事实上,我在现实中遇到了一个复杂的问题,我在这里简化了:)感谢您提供的解决方案传递参数hello
在name
函数中是无用的。无论您提供什么,JS引擎都会首先查找函数而不是参数,然后进行求值。@MunimAbdul尝试运行该代码而不传入参数。它不调用hello函数。