2016-04-12 35 views
2

Yeni JavaScript ile. Birisi bana neden print() undefined döndürdüğünü anlamama yardımcı olabilir?Javascript sınıfı yapılandırılmış nesne tanımlanmamış

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

Oluşturma: En koduyla

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

printAllQuestions() nerede? –

+0

Sonunda hata yaptım. PrintAllQuestions() değil print() demek istedim – blueman

cevap

6

sorunlar,

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 

Çözüm:

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

sınıf sözdizimi ile çok aşina değilseniz henüz Aşağıdakiler de çalışmalıdır.

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();