2016-05-31 212 views
0

不能爲我工作了,爲什麼其中任一不工作:爲什麼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

沒有函數或方法'cards'。 'cards'是一個有數組的屬性。正確的調用將是'console.log(newDeck.cards);' –

+0

@ NinaScholz在第二個例子中有一個卡片功能,雖然?? – hellogoodbye

+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

在你的例子中,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());

相關問題