实现两个js文件之间函数的互相调用,本文介绍三种方法,直接上代码。
1、在<body>标签结束之前以下面的方式引入两个js文件
//index.js
<html>
<head>
</head>
<body>
<script type = "text/javascript" src="a.js"></script>
<script type = "text/javascript" src="b.js"></script>
<script type = "text/javascript">
document.addEventListener("DOMContentLoaded",function(){
console.log("DOMContentLoaded")
ACode() //a.js或者b.js中函数
})
</body>
//a.js文件
var ACode = function(){
cosole.log("ACode")
}
//b.js文件
ACode() //a.js 文件中函数ACode调用
var BCode() = function{
cosole.log("BCode")
}
在a.js、b.js中定义函数时要注意,使用函数表达式,不要使用函数声明,否则会出现函数id not defined(两者的区别:解析器会先读取函数声明,并使其在执行任何代码之前可以访问;而函数表达式则必须等到解析器执行到它所在的代码行才会真正被解释执行。)
2、若要在b.js中调用a.js中函数ACode内部之间的函数,可以使用原型继承。如下:
//index.js
<html>
<head>
</head>
<body>
<script type = "text/javascript" src="a.js"></script>
<script type = "text/javascript" src="b.js"></script>
<script type = "text/javascript">
document.addEventListener("DOMContentLoaded",function(){
console.log("DOMContentLoaded")
ACode() //a.js或者b.js中函数
})
</body>
//a.js文件
function ACode(){
cosole.log("ACode")
this.Afun1 = function(){ //该函数在b.js中可调用
console.log('1')
}
var Afun2 = function(){ //该函数在b.js中不可调用。若放在ACode外面可以被b.js调用
console.log('2')
}
}
//b.js文件
var BCode() = function{
this.Aobject = new ACode(); //创建Acode的实例对象
this.Aobject.Afunc1()
cosole.log("BCode")
}
3、在a.js中文件中调用b.js文件中的函数,已知:index.html中已引入a.js文件。
//index.js
<html>
<head>
<script src="a.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
//a.js文件
function ACode(){
cosole.log("ACode")
}
//b.js文件
function BCode(){
cosole.log("BCode")
}
要求:上述html内容不变的情况下,在a文件引入b.js中函数。实现如下:
//a.js文件中修改
//a.js文件
function ACode(){
var head = document.getElementsByTagName('head');
var testScript = document.createElement('script');
testScript.src = "b.js";
testScript.type = 'text/javascript';
head[0].appendChild(testScript);
Bcode(); //调用b.js文件中函数
cosole.log("ACode")
}