Shimul Bodruddoza
Shimul Bodruddoza

Reputation: 11

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'.

Upvotes: 0

Views: 984

Answers (1)

Frederik
Frederik

Reputation: 46

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);

Upvotes: 3

Related Questions