Stack Guru
Stack Guru

Reputation: 871

Weird JavaScript statement, what does it mean?

I see this code, what's it doing?

var obj = this;

Upvotes: 0

Views: 219

Answers (8)

Town
Town

Reputation: 14906

It's creating a variable 'obj' and setting it to the current context.

So, for example, if it's at a global level this would be the current DOM Window.

Upvotes: 1

jhurshman
jhurshman

Reputation: 6067

The only context I can think of where this sort of code makes sense is to make the current context (this) available inside a closure.

So the code would be something like:

var obj = this;
setTimeout(function() {
    obj.someMethod();
}, 1000);

That would call the method "someMethod" on the current context object after 1 second goes by.

Upvotes: 0

Scherbius.com
Scherbius.com

Reputation: 3414

It depends where this statement is located. It assigns to variable "obj" reference to current object.

for example the following code will open an alert window and show [Window object]. That's because we check value of "this" in the body area (not inside any objects event handler, etc.)

<html>
    <head>
    </head>
    <body>

    <script type="text/javascript">

        alert(this);
    </script>   

    </body>
</html>

Upvotes: 1

wildcard
wildcard

Reputation: 7503

It's just storing the current reference of this object, to be used in future. It's useful, because in JS value of this depends on a context.

Upvotes: 5

gen_Eric
gen_Eric

Reputation: 227240

It saves a reference to whatever this was in the current context, so it can be used later.

Upvotes: 3

Neeraj
Neeraj

Reputation: 8532

The this keyword is used to refer to the owner of the function , or the variable the this keyword is used in. For a detailed understanding visit http://www.quirksmode.org/js/this.html

Upvotes: 0

Mike Lewis
Mike Lewis

Reputation: 64147

var obj = this;

Is stating, assign obj with the parent of the current scope.

I first read this post a couple months ago to get a handle on the keyword 'this'.

http://justin.harmonize.fm/index.php/2009/09/an-introduction-to-javascripts-this/

Upvotes: 0

Jake Kalstad
Jake Kalstad

Reputation: 2065

That is setting a local copy of the current first class function that its being set in.

This is used ALOT in jquery as this takes on a different meaning when you being using the selectors.

Say I have a

function Person() {
   this.name = "gnostus";
}

and I need to access name from inside a jquery selector, where this becomes an html element, I would store my object into a copy variable and use, obj.name in place of this.name when im inside of the jquery context.

Upvotes: 1

Related Questions