Skip to content Skip to sidebar Skip to footer

Weird JavaScript Statement, What Does It Mean?

I see this code, what's it doing? var obj = this;

Solution 1:

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.


Solution 2:

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


Solution 3:

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.


Solution 4:

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>

Solution 5:

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.


Post a Comment for "Weird JavaScript Statement, What Does It Mean?"