[英]Get reference to variable inside anonymous function
Say I'm writing a greasemonkey/chrome extension script that needs access to a variable that's inside of a closured anonymous method, like so 假设我正在编写一个润滑脂猴子/ chrome扩展脚本,该脚本需要访问封闭匿名方法内部的变量,例如
$(document).ready(function() {
var goldenTreasure = "Tasty Loins";
}
is there any way I can get to that goldenTreasure and have me some tasty loins? 有什么办法可以让我获得GoldenTreasure并给我一些美味的里脊肉?
Define the variable outside, then assign value inside. 在外部定义变量,然后在内部分配值。
var goldenTreasure;
$(document).ready(function() {
goldenTreasure = "Tasty Loins";
}
Or another way of doing it is to assign it as a property of the window object 或执行此操作的另一种方法是将其分配为window对象的属性
$(document).ready(function() {
window.goldenTreasure = "Tasty Loins";
}
You can declare a variable outside of the anonymous function and just assign the one inside as its value. 您可以在匿名函数外部声明一个变量,然后将其内部的值赋值即可。 (do it this way if you plan to reuse
goldenTreasure
for another purpose inside the anonymous function. (如果您打算在匿名函数
goldenTreasure
用于其他目的,请按照这种方式进行操作。
var some;
$(document).ready(function() {
var goldenTreasure = "Tasty Loins";
some = goldenTreasure;
}
There is no way to access a var
that's inside a closure as it is a private variable
that is technically hidden inside the containing closure. 无法访问闭包内部的
var
,因为它是一个private variable
,从技术上讲它隐藏在包含的闭包内部。 Only functions inside that closure may have access to it. 只有该闭包内部的函数才可以访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.