开发者

What is the "this" pointer for global functions? [duplicate]

开发者 https://www.devze.com 2023-03-18 14:45 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: 'this' keyword, not clear
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号