简体   繁体   English

将“ this”引用分配给javascript中的变量

[英]Assign 'this' reference to a variable in javascript

Is it possible to assign 'this' reference to a variable in javascript. 是否可以将“ this”引用分配给javascript中的变量。 What I want is: 我想要的是:

var someVariable = this;
alert(someVariable);

But I'm getting alert saying 'undefined'. 但是我越来越警惕地说“未定义”。

Yes, it is possible to assign this to a variable. 是的,这是可以分配this一个变量。 When you get undefined , then you probably use/alert the variable outside the scope where it was defined. 当您获得undefined ,您可能会在定义范围之外使用/更改变量。

This will work: 这将起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM