为什么这个JavaScript无法正常工作?

时间:2016-05-31 16:02:00

标签: javascript

无法解决为什么其中任何一个对我不起作用:

var Deck = function() {
  this.cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
};

var newDeck = new Deck

// console.log(newDeck()); // [1,2,3,4,etc]

console.log(newDeck.cards()); // [1,2,3,4,etc]

returns newDeck.cards is not a function

var Deck = function() {
  this.cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  var cards = function(){
    console.log('hey')
  }
};

var newDeck = new Deck

// console.log(newDeck()); // [1,2,3,4,etc]

console.log(newDeck.cards()); // [1,2,3,4,etc]

returns the same error as above

我只想从实例

返回对象中的函数

2 个答案:

答案 0 :(得分:1)

没有任何功能或方法cardscards是一个带数组的属性。正确的电话会是

console.log(newDeck.cards);



var Deck = function() {
    this.cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
};

var newDeck = new Deck;

console.log(newDeck.cards); 




第二个例子包含一个私有函数cards。由于私有字符,该函数不能在外部调用。

答案 1 :(得分:1)

在您的示例中,this.cards将是属性,而不是函数。如果您想要一个适用于所有Deck实例的函数:

var Deck = function() {
    // `_cards` so we do not conflict with the `cards` function
    this._cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
};

Deck.prototype.cards = function() {
  return this._cards;
};

var deck = new Deck();
console.log(deck.cards());

相关问题