无法在方法中设置undefined属性'var'

时间:2014-09-15 17:18:53

标签: javascript html5 angularjs angularjs-scope

我在这里做了一件非常简单的事情,但却说错误

  

TypeError:无法设置属性'问题'未定义的       在setQuestion

我无法弄清楚导致它的原因。我是AngularJS的新手,所以我可能会离开这里,但它与$ scope有什么关系吗?

 var questions = [
                    { header:"Hello World 1", body:["1 dfhgjkmhngfsdgfhytgh", "1 dfhgjkmhngfsdgfhytgh"], answer:"dfghf"},
                    { header:"Hello World 2", body:["2 dfhgjkmhngfsdgfhytgh"], answer:"dfghf"},
                    { header:"Hello World 3", body:["3 dfhgjkmhngfsdgfhytgh", "1 dfhgjkmhngfsdgfhytgh", "1 dfhgjkmhngfsdgfhytgh"], answer:"dfghf"},
                    { header:"Hello World 4", body:["4 dfhgjkmhngfsdgfhytgh"], answer:"dfghf"},
                    { header:"Hello World 5", body:["5 dfhgjkmhngfsdgfhytgh"], answer:"dfghf"}
                ];

        this.question = {};

        var setQuestion = function(index){
            this.question = questions[index];
        }

        setQuestion(0);
        console.log("Question is: " + this.question.header);

感谢任何帮助或解释

1 个答案:

答案 0 :(得分:0)

var setQuestion = function(index){
    this.question = questions[index];
}
在此上下文中,

this是您的函数 setQuestion,而不是您在上面声明的对象。它与说setQuestion.question相同,但尚未宣布。

将您的this.question = {};更改为var question = {},并在功能内将this.question更改为question,使其看起来像

var question = {};

var setQuestion = function(index){
   question = questions[index];
}