js文件之间函数的调用

实现两个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")
}

 

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值