0

I'm doing something really simple here but getting an error saying

TypeError: Cannot set property 'question' of undefined at setQuestion

and I cannot figure out what's causing it. I'm new to AngularJS so I might be way off here but does it have anything to do with the $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);

Appreciate any help or explanation

thehindutimes
  • 321
  • 1
  • 6
  • 19

1 Answers1

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

this in this context is your function setQuestion, and not the object your declared above. It is the same as saying setQuestion.question, which has not been declared.

Change your this.question = {}; to var question = {}, and inside the function change this.question to just question so that it looks like

var question = {};

var setQuestion = function(index){
   question = questions[index];
}
ScottW
  • 421
  • 2
  • 7
  • 1
    *"`this` in this context is your function `setQuestion`"* No, it definitely is not. *"It is the same as saying `setQuestion.question`, ..."* Nope. You are right that `this` inside the function does not refer to the same value as `this` outside of the function, but it does not refer to the function itself. – Felix Kling Sep 15 '14 at 17:24
  • Yes, you got it correct. However, the gist of it is that they are not referencing the same value. – ScottW Sep 15 '14 at 17:29
  • 1
    Right, but nevertheless your answer contains false information. – Felix Kling Sep 15 '14 at 17:32
  • 1
    @ScottW Given the [intricacies of `this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) in JavaScript, it is best to make sure your information is accurate and correct, rather than getting "the gist of it". – ajp15243 Sep 15 '14 at 17:33