2016-05-31 210 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());

相关问题