Assign 'this' reference to a variable in javascript

偶尔善良 提交于 2020-01-07 02:16:10

问题


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


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


来源:https://stackoverflow.com/questions/37627344/assign-this-reference-to-a-variable-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!