2016-05-31 3 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

Нет функции или метода cards. cards - свойство с массивом. Право вызова будет

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());

Смежные вопросы