如何从其他文件创建另一个类的实例

时间:2017-07-19 18:03:39

标签: javascript node.js oop

我已经搜遍了这个非常简单的问题的一个可理解的答案,似乎找不到一个。作为一名主要的java程序员,这是一个非常令人沮丧的过程。

例如,假设我正在尝试编制一副牌。我这样做的方法是在card.js中有一个'Card'类,看起来像这样:

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

}

然后在deck.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(再次,对不起,我是这个环境的新手)。或者更好地说明,这将是服务器端。

2 个答案:

答案 0 :(得分:1)

您需要使用导出和导入:

在卡片文件中,您可以:

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
};

答案 1 :(得分:1)

您可以使用模块系统

在你的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
 }
相关问题