1

JSFiddle

Question: Why is this.decks.push(data); coming up undefined? How can I get deckCtrl.decks to properly log out?

Error: 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); 

1 Answer 1

2

You need to use new to create a new instance:

var deckBuilder = new Deck();
var deckCtrl = new DeckController();

And you want to use the addDeck of the instance, not of the prototype:

DECK_DATA.cards.forEach(function (item) {
    deckCtrl.addDeck(new deckBuilder(item));
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.