问题:为什么this.decks.push(data);
未定义?如何让deckCtrl.decks
正确注销?
错误:
Uncaught TypeError: Cannot read property 'push' of undefined
var DECK_DATA = {};
DECK_DATA.cards = [
{
faces: [
{
name: 'a',
src: '',
link: ''
},
{
name: 'b',
src: '',
link: ''
},
{
name: 'b',
src: '',
link: ''
}
]
},
{
faces: [
{
name: 'a',
src: '',
link: ''
},
{
name: 'b',
src: '',
link: ''
},
{
name: 'b',
src: '',
link: ''
}
]
}
];
//Classes
var Deck = (function () {
function Deck(card) {
this.cards = card;
}
return Deck;
})();
var DeckController = (function () {
function DeckController() {
this.decks = [];
}
DeckController.prototype.addDeck = function (data) {
console.log(data, this.decks); //this.decks comes up undefined.
this.decks.push(data);
};
return DeckController;
})();
//main
var deckBuilder = Deck;
var deckCtrl = DeckController;
DECK_DATA.cards.forEach(function (item) {
deckCtrl.prototype.addDeck(new deckBuilder(item));
});
console.log(deckCtrl.decks);
答案 0 :(得分:2)
您需要使用new
来创建新实例:
var deckBuilder = new Deck();
var deckCtrl = new DeckController();
你想使用实例的addDeck,而不是原型:
DECK_DATA.cards.forEach(function (item) {
deckCtrl.addDeck(new deckBuilder(item));
});