2016-04-12 118 views
2

JavaScript新增功能。有人可以幫我理解爲什麼呼叫print()返回undefined?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

where is printAllQuestions()? –

+0

我的錯誤是我的錯誤。我的意思是print(),而不是printAllQuestions() – 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();