2016-04-12 9 views
2

Neu mit JavaScript. Kann mir jemand helfen zu verstehen, warum der Aufruf print() undefined zurückgibt?Javascript Klasse konstruiertes Objekt ist undefined

class Quizer { 
    constructor(quizObj) { 
     this.quiz = quizObj; 
    } 
    print() { 
     console.log(quiz.title); 
    } 
}; 
var quizObjects = { 
    title: "Quiz1" 
}; 

Constructing:

var quiz = new Quizer(quizObjects); 
quiz.print(); //undefined 
+0

wo ist printAllQuestions()? –

+0

Ah Fehler an meinem Ende. Ich meinte print(), nicht printAllQuestions() – blueman

Antwort

6

Die Probleme mit Ihrem Code sind,

class Quizer { 
    constructor(quizObj) { 
     this.quiz = quizObj; 
    } 
    print() { 
     console.log(quiz.title); 
     //You are not using the `this` context here to access the quiz 
     //you have a variable quiz outside the class declaration that points the instance of this class. 
    //That will get hoisted and will be accessed here. 

    } 
}; 

var quizObjects = { title: "Quiz1" }; 
var quiz = new Quizer(quizObjects); 
quiz.printAllQuestions(); //undefined 
//--------^^^^ printAllQuestions is not a member function of Quizer 

Lösung:

class Quizer { 
    constructor(quizObj) { 
     this.quiz = quizObj; 
    } 
    print() { 
     console.log(this.quiz.title); 
    } 
}; 

var quizObjects = { title: "Quiz1" }; 
var quiz = new Quizer(quizObjects); 
quiz.print(); //Quiz1 
1

Wenn Sie nicht viel vertraut mit Klasse Syntax sind noch sollte das unten auch funktionieren.

Quizer = function (quizObj) { 
    this.quiz = quizObj; 
}; 
Quizer.prototype = { 
    print: function() { 
     console.log(this.quiz.title); 
    } 
} 
var quizObjects = { title: "Quiz1" }; 
var quiz = new Quizer(quizObjects); 
quiz.print(); 
Verwandte Themen