0

I am looping over a simple object using forEach function, I'm passing the object as the context.

When I try to access an object property using this[key] it works but this.key doesn't work, can someone tell us why it behaves so?

var calendar =  {
        moveAll: false,
        moveSingleDay: false,
        translateRange : false
}

angular.forEach(calendar, function(val, key){
      console.log(this[key]); // returns val
      console.log(this.key); // returns undefined
}, calendar);
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
badr slaoui
  • 1,023
  • 11
  • 27
  • Possible duplicate of [Dynamically access object property using variable](http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Rajesh Jan 05 '16 at 10:05

3 Answers3

5

this.key is equivalent to this['key'].

freakish
  • 54,167
  • 9
  • 132
  • 169
  • this['key'] allow you to do ... var str = 'key' ... this[str] ... thus you can dynamically access properties – danday74 Jan 05 '16 at 10:18
2

That is because your calendar object has no property named key.

Note: In the expression this.key key won't be replaced by the value of variable named key.

Victor Dombrovsky
  • 2,955
  • 3
  • 21
  • 33
0

The key variable will contain the indexes of your array, for example: (1,2,3...) what you are trying to do when you type this.key is like this.1 that why you get undefined

Anas Youbi
  • 65
  • 6