0

I see statements like this inside a quojs javascript library:

return r(e,this[0].className)

or

return this[0].style[e]||n(this[0],e)

I know from the documentation that this refers to the "global object." But what does the array mean? The array of properties of the global object?

bernie2436
  • 22,841
  • 49
  • 151
  • 244
  • 4
    You have to track down the context. `this` depends on how the function is called, it's dynamic, and can be changed at runtime. – elclanrs Dec 05 '13 at 00:40
  • intereting question, heres another answer about what exactly 'this' might refer to http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal – actual_kangaroo Dec 05 '13 at 00:41
  • From looking at the code though, I would say `this` is a NodeList. – elclanrs Dec 05 '13 at 00:45
  • The MDN documentation also explains which other values `this` can have. – Felix Kling Dec 05 '13 at 00:56

1 Answers1

2

The value of this depends on many things, and you can't tell from that snippet of code.

For example:

var person = {
  name: "Bob",
  sayHi: function() {
    alert(this.name + " says hi!");
  }
};

person.sayHi();

In this example, this refers to person when the sayHi() method is invoked. But If all I posted was this:

alert(this.name + " says hi!");

There would be no way to tell what the value of this is. this is known as the context, so the context in which it appears is important!

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • what are the contexts in which this can take on the properties of an array? – bernie2436 Dec 05 '13 at 09:53
  • When an array is the receiver of a method invocation. `myArray.foo()`, `this` is equal to `myArray` within `foo`. But _any_ javascript object (which includes arrays) can be access with the `obj[key]` notation. – Alex Wayne Dec 05 '13 at 18:20