2016-04-12 39 views
2

JavaScriptで新たに追加されました。誰かが私になぜを呼び出すのが未定義を返すのか理解できるように助けることができますか?Javascriptクラスの作成オブジェクトは定義されていません

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

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

printAllQuestions()はどこですか? –

+0

ああ、間違いだよ。私はprintAllQuestions()ではなくprint() – blueman

答えて

6

をあなたのコードに問題が、

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 

ソリューションです:あなたはまだクラスの構文とあまり慣れていない場合は

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

、以下も同様に機能するはずです。

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(); 
関連する問題