What is the "this" pointer for global functions? [duplicate]
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 开发者_Go百科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.
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.
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
.
The this member refers to the entire page, and will always be defined - your foo() method will never return null.
this
always points on the current element. In the case of foo()
, this
points to window
.
精彩评论