外部Javascript从另一个外部Javascript文件调用函数

External Javascript calling functions from another external javascript file

本文关键字:外部 Javascript 调用 函数 另一个 文件      更新时间:2023-09-26

所以,我看了其他类似的问题,但他们并没有真正回答这些问题。

简言之:我使用过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;
}

在项目.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.中

希望这能帮助你。。。