我想创建一个在方法内全局访问的变量。 (我认为我使用了正确的术语)。
例如,jQuery 的 .hover()
。在其中,我试图动态访问一个类名并将其存储起来,以便以后在原始 .hover()
$('elem').hover(function() {
var classname = $(this)something;
return classname;
});
console.log(classname);
我正在尝试在全局范围内使用它,因为它影响的方法不仅仅是这个方法。
我确信我应该使用一种完全不同的编程方法来完成这项工作,但在方法之外返回值似乎是我的小知识库唯一可用的过程。
最佳答案
你有几个选择:
在您的代码周围使用范围函数,并在该范围函数内使用局部变量。作用域函数内的所有函数都可以访问这些变量:
(function() { var classname = ""; $('elem').hover(function() { classname = this.className; }); $('some other elem').on('some-other-event', function() { console.log(classname); }); })();
请注意第二个事件处理程序如何访问
hover
处理程序可以访问的同一个变量。在这两种情况下,它们都有一个对变量的持久引用,而不是变量的副本。更多:Closures are not complicated .使用全局变量,这基本上只是上面的一个特例。
我推荐#1。这是一个完整的示例:Live Copy | Source
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Simple Closure</title>
<style>
.a, .b, .c {
width: 60px;
border: 1px solid black;
}
</style>
</head>
<body>
<p>Hover over these:</p>
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>
<script>
(function() {
var prevClassHovered = "";
var lastClassHovered = "";
// Remember the last hovered thing
$(".a, .b, .c").hover(function() {
lastClassHovered = this.className;
});
// Output the last one every ~500 ms, if it's
// changed. Here the event in question is a
// timer event, but of course it can be anything.
setInterval(function() {
if (prevClassHovered !== lastClassHovered) {
prevClassHovered = lastClassHovered;
display(lastClassHovered);
}
}, 500);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
关于javascript - 从方法返回全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20817087/