Skip to content Skip to sidebar Skip to footer

Assign 'this' Reference To A Variable In Javascript

Is it possible to assign 'this' reference to a variable in javascript. What I want is: var someVariable = this; alert(someVariable); But I'm getting alert saying 'undefined'.

Solution 1:

Yes, it is possible to assign this to a variable. When you get undefined, then you probably use/alert the variable outside the scope where it was defined.

This will work:

var someVariable;
function someFunction () {
    someVariable = this;
}
new someFunction();
alert(someVariable);

Post a Comment for "Assign 'this' Reference To A Variable In Javascript"