1

Possible Duplicates:
'this' keyword, not clear
this operator in javascript

function foo()
{
    if(this === window)
        return null;

    return 1;
}

var i = foo(); // returns 1;

What is the this member of a global function, and how can I test from within a function if it's being called in a global scope or as a member function?

Edit: It seems JQuery makes a difference here, since everybody assures me foo should return null for run-of-the-mill JavaScript. How does JQuery change this?

Note that the OP says, in a comment, below, that this is in a Greasemonkey script.

Community
  • 1
  • 1
bfops
  • 4,428
  • 4
  • 28
  • 41

4 Answers4

3

this refers to the window object in this case.

Just do alert(this); and it will say [object Window]

But if you do

var i = new foo(); // returns an object (instance of foo);

then this refers to the instance of foo.

Gabriele Petrioli
  • 173,972
  • 30
  • 239
  • 291
3

According to this the difference is because of greasemonkey (not JQuery).

A Greasemonkey user script, however, by default wraps up all code inside an anonymous function wrapper that swallows identifiers, causing them not to end up on the global object.

It goes on to say that you can use @unwrap to make this point to the window as it does with regular on-page Javascript.

trutheality
  • 21,548
  • 6
  • 47
  • 65
0

The this member refers to the entire page, and will always be defined - your foo() method will never return null.

MuffinMan
  • 861
  • 1
  • 7
  • 27
-1

this always points on the current element. In the case of foo(), this points to window.

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
aruss
  • 354
  • 1
  • 13