2016-04-12 77 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();