簡體   English   中英

如何從其他文件創建另一個類的實例

[英]How can I create an instance of another class from a different file

我到處搜尋了一個非常簡單的問題的可理解答案,似乎找不到一個。 作為一個主要的Java程序員,這是一個非常令人沮喪的過程。

例如,假設我正在嘗試編程一副紙牌。 我這樣做的方法是在card.js中有一個“ Card”類,它看起來像這樣:

function Card(value, suit){
  this.value = value;
  this.suit = suit;

}

然后是eck.js中的“ Deck”類,看起來像這樣:

function Deck(){
  this.cardArray = [];
  this.topCard = new Card(2, 'clubs');
}

Deck.prototype.shuffle = function(){
    //shuffle the deck
}

這里的問題是我得到一個錯誤消息,提示“意外的標識符”。 大概是因為js沒有意識到我已經定義了Card類。 我該如何做,以便deck.js文件可以訪問Card類?

我應該提到我正在嘗試在沒有瀏覽器的情況下執行此操作,因此我認為我將使用node.js(同樣,很抱歉,我是這個環境的新手)。 也許更好地說,這將是服務器端。

您需要使用進出口:

在卡文件中,您將執行以下操作:

function Card(num, suit) {
    this.num = num;
    this.suit = suit
}

module.exports = Card;

然后在Deck文件中,您將執行以下操作:

var Card = require('./Card.js');

function Deck() {
    this.cardArray = [];
    this.topCard = new Card(2, 'clubs');
}

Deck.prototype.shuffle = function () {
    //shuffle the deck
};

您可以使用模塊系統

在您的card.js中:

const Card = function(value, suit){
 this.value = value;
 this.suit = suit;
}
module.exports = Card;

並在您的deck.js中

const Card = require('./card');

function Deck(){
 this.cardArray = [];
 this.topCard = new Card(2, 'clubs');

}

 Deck.prototype.shuffle = function(){
   //shuffle the deck
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM