Javascript 调用文件中的函数,而被调用函数调用第一个文件中的另一个函数
我在调用另一个文件中的函数时遇到问题,而在第二个文件中,被调用的函数必须调用第一个文件中的另一个函数。这怎么可能? 在我的示例中,我首先调用File2.js中的Printer1函数,然后在File2.js中调用File1.js中声明的Printer2(但我没有在File2.js中包含File1.js,但我在File1.js中进行了调用(包括File2.js) File1.jsJavascript 调用文件中的函数,而被调用函数调用第一个文件中的另一个函数,javascript,jquery,Javascript,Jquery,我在调用另一个文件中的函数时遇到问题,而在第二个文件中,被调用的函数必须调用第一个文件中的另一个函数。这怎么可能? 在我的示例中,我首先调用File2.js中的Printer1函数,然后在File2.js中调用File1.js中声明的Printer2(但我没有在File2.js中包含File1.js,但我在File1.js中进行了调用(包括File2.js) File1.js var data1="Hi"; Printer1(data1); var Printer2(){ document.w
var data1="Hi";
Printer1(data1);
var Printer2(){
document.write(data1);
}
File2.js:
var Printer(data1){
document.write(data1);
Printer2();
}
另外,我想知道是否可以在页面的开头包含File2.js,或者在调用Printer1之前必须包含一行?您的javascript将按照加载顺序执行,而不是提升,如果使用正确的语法,在编写函数之前可以使用函数
File 1:
function foo() {
alert("I'm foo!");
}
File 2:
foo(); //alerts "I'm Foo!"
基本上,有两个文件,比如
这和将它们组合在一起一样。如果它是这样工作的,那么它也将单独工作,而不是吊装
这是起重作业的方式:(必须在同一文件中,在同一范围内)
这是因为以这种方式定义的函数将“提升”到该范围内执行的开始
哪些不起作用:
foo(); //undefined!!
var foo = function() { //doesn't get hoisted!
alert("I'm foo!");
}
如果您想要提升,请使用其他语法
有一件事你可能想知道,但我真的搞不懂你的问题(令人困惑的措辞,哈哈)
如果文件1的函数使用了文件2中的函数,该怎么办?在这种情况下,您将无法使用文件1中的函数,因为在执行文件1时,文件2中的函数将是未定义的,但您可以使用文件2中的文件1函数(即使在开始时已将其挂起) 像这样:
File 1:
function foo() {
bar();
}
foo(); //bar is undefined! error!
File 2:
foo(); //works!! bar is hoisted and therefore defined already for "foo" to use
function bar() {
alert('from file 2!');
}
首先,您应该在var中使用函数。您不应该使用document.write.Check out。JS应该如下所示: file1.js:
var data1="Hi";
Printer1(data1);
function Printer2(){
document.write(data1);
}
file2.js
function Printer1(data1){
document.write(data1);
Printer2();
}
为了使file2中的函数可调用,您需要如下所示的标记:
<body>
<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript" src="file1.js"></script>
</body>
What???另外,停止使用document.write()
var-Printer(data1){
无效吗?应该是var-Printer=function(data1){
这个问题的标题伤了我的大脑。@Rorymcrossan原因检查用户名。这甚至不是有效的JavaScript。
<body>
<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript" src="file1.js"></script>
</body>