[英]External Javascript calling functions from another external javascript file
因此,我查看了其他类似问题,但他们并没有真正回答这些问题。
简而言之:我使用过HTML,Java,VB和MIRC使用的任何语言(不到10年的时间)。
我是javascript的新手,但是由于我拥有其他计算机语言知识,所以……我知道使用Java可以创建类和类的函数。
但是,对于html / javascript,我不确定如何从一个外部.js文件调用函数到另一个。
假设:我想创建一个可以随时调用函数的播放器类,并在“ main” .js文件中使用它,该文件在另一个函数中使用该类中的那些函数。 例如。
如果我有
function isDead() {
if (health < 10 || energy < 10)
{
return dead = 'true';
}
else { return dead; }
}
在Player .js文件中,在主文件中,我有。
function fight() {
if (isDead() == 'true')
{
energy -= 10;
health -= 10;
Swords();
}
document.getElementById("energy").innerHTML = energy;
document.getElementById("health").innerHTML = health;
document.getElementById("sword").innerHTML=sword;
}
在item.js中,我有
var swordDamage = 0;
function Swords(){
if (swordDamage < 3)
swordDamage +=1;
else
return sword -=1;
}
(请记住,这实际上是有效的(我尚未针对这个问题进行剑的测试)。
我需要从其他.js文件将这些函数调用到main.js文件中的任何特殊方法。
例如:main.function();
还是我最好把它们另存为html文档,只写脚本来解决这个问题?
谢谢回答!
我来自与您相同的环境。 我完成了对我有很大帮助的JavaScript课程codeacademy.com。
好吧,我应该像这样实现您的示例:
fighter.js
function Fighter(){
this.health = 100;
this.energy = 100;
this.isDead = function() {
if (health < 10 || energy < 10)
{
return dead = 'true';
}
else {
return dead;
}
}
this.Punch = function(otherFighter){
otherFighter.energy -= 10;
otherFighter.health -= 10;
}
this.AtackWithItem(item, fighter){
otherFighter.energy -= item.damage;
otherFighter.health -= item.damage;
}
}
main.js
function initFight() {
var fighterA = new Fighter();
var fighterB = new Fighter();
document.getElementById("energy").innerHTML = energy;
document.getElementById("health").innerHTML = health;
document.getElementById("sword").innerHTML=sword;
fighterB.punch(fighterA);
document.getElementById("energy").innerHTML = energy;
document.getElementById("health").innerHTML = health;
document.getElementById("sword").innerHTML=sword;
var sword = new item();
fighterA.AtackWithItem(sword,fighterB);
document.getElementById("energy").innerHTML = energy;
document.getElementById("health").innerHTML = health;
document.getElementById("sword").innerHTML=sword;
}
item.js
function item(){
this.type = "Swords"
this.damage = 20;
}
所有文件fighter.js,main.js和item.js将以标记引用:
<script src="../item.js"></script>
<script src="../fighter.js"></script>
<script src="../main.js"></script>
在index.html中。
希望这对您有帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.