[英]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.