无法从javascript中的原型访问构造函数的值?

时间:2016-02-07 03:20:21

标签: javascript arrays oop constructor prototype

JSFiddle

问题:为什么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); 

1 个答案:

答案 0 :(得分:2)

您需要使用new来创建新实例:

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

你想使用实例的addDeck,而不是原型:

DECK_DATA.cards.forEach(function (item) {
    deckCtrl.addDeck(new deckBuilder(item));
});