1

I see this code, what's it doing?

var obj = this;
Stack Guru
  • 873
  • 2
  • 8
  • 7

8 Answers8

5

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.

wildcard
  • 7,353
  • 3
  • 27
  • 25
3

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

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

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.

Town
  • 14,706
  • 3
  • 48
  • 72
1

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.

Jake Kalstad
  • 2,045
  • 14
  • 20
1

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>
Scherbius.com
  • 3,396
  • 4
  • 24
  • 44
0
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/

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
0

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

Neeraj
  • 8,408
  • 8
  • 41
  • 69
0

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.

jhurshman
  • 5,861
  • 2
  • 26
  • 16