javascript - 从方法返回全局变量

标签 javascript methods scope

我想创建一个在方法内全局访问的变量。 (我认为我使用了正确的术语)。

例如,jQuery 的 .hover()。在其中,我试图动态访问一个类名并将其存储起来,以便以后在原始 .hover()

范围之外的其他方法和函数中进行操作
$('elem').hover(function() {
    var classname = $(this)something;
    return classname;
});

console.log(classname);

我正在尝试在全局范围内使用它,因为它影响的方法不仅仅是这个方法。

我确信我应该使用一种完全不同的编程方法来完成这项工作,但在方法之外返回值似乎是我的小知识库唯一可用的过程。

最佳答案

你有几个选择:

  1. 在您的代码周围使用范围函数,并在该范围函数内使用局部变量。作用域函数的所有函数都可以访问这些变量:

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

  2. 使用全局变量,这基本上只是上面的一个特例。

我推荐#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/

相关文章:

javascript - 通过一个 ref 访问多个元素 React

javascript - ajax调用后删除元素

objective-c - 在文档加载时执行 Objective-C 方法

swift - Swift 中的类内部协议(protocol)

javascript - Bootstrap + 弹出窗口 - skype href 链接不起作用

javascript - 无法加载资源 : the server responded with a status of 401 for mapbox api

java - 创建同一类的多个对象的更简单方法

java - 如何避免像 "This method must return a result of type int"这样的错误?

python - 作用域静态确定动态使用是什么意思?

c++ - 在范围内定义的变量与注入(inject)该作用域的命名空间变量