【问题标题】:can't understand the parameter after JS functionJS函数后的参数看不懂
【发布时间】:2018-10-17 03:13:01
【问题描述】:

有人写了这个函数来检测鼠标。但我真的不明白它是如何工作的。所以我对这个函数没有几个问题。

 document.onmousemove = (function() {
  var onmousestop = function() {
    /* do stuff */
    console.log('STOP');
  }, thread;

  return function() {
 clearTimeout(thread);
    console.log(thread);
    thread = setTimeout(onmousestop, 500);
    
  };
})();

有一部分我们有 function(){},thread; 那部分实际上是什么意思?函数的}后面的参数是什么意思?

【问题讨论】:

  • 就像var x = 5, y = 6一样,一次声明两个变量,而开头只使用一个var(或letconst

标签: javascript function


【解决方案1】:
var onmousestop = function() {
        /* do stuff */
        console.log('STOP');
    }, thread;

等价于

var onmousestop = function() {
        /* do stuff */
        console.log('STOP');
    };
var thread;

返回函数

return function() {
    clearTimeout(thread);
    console.log(thread);
    thread = setTimeout(onmousestop, 500);
};

正在做两件事。 1) clearTimeout(thread); 取消对onmousestop 的任何先前安排的(且仍待处理的)呼叫。 2) thread = setTimeout(onmousestop, 500); 安排在 500 毫秒内调用 onmousetop 并将 thread 设置为本质上是标识计划操作的 ID(以便可以取消它)。

【讨论】:

  • @MAHDI,我已经更新了我的答案来解释返回函数。
【解决方案2】:

您可以一次声明多个变量,方法是用逗号分隔它们。

var a = function(){}, thread;

这意味着a 是一个空函数,thread 被声明但undefined

thread 是在返回的第一个函数中声明的变量,然后在第二个函数中初始化。

超时会在 500 毫秒后导致递归函数调用,其中再次调用初始函数。

【讨论】:

    【解决方案3】:

    让我们一步一步来

    (function() {
      var onmousestop = function() {
        /* do stuff */
        console.log('STOP');
      }, thread;
    
      return function() {
     clearTimeout(thread);
        console.log(thread);
        thread = setTimeout(onmousestop, 500);
    
      };
    })();
    

    这是一个自运行功能,与

    相同
    function t() {
          var onmousestop = function() {
            /* do stuff */
            console.log('STOP');
          }, thread;
    
          return function() {
            clearTimeout(thread);
            console.log(thread);
            thread = setTimeout(onmousestop, 500);
    
          };
        }
    t()
    

    所以代码是这样的:

    var onmousestop = function() {
        /* do stuff */
        console.log('STOP');
    };
    var thread;
    document.onmousemove = function() {
    clearTimeout(thread);
        console.log(thread);
        thread = setTimeout(onmousestop, 500);
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-10
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      相关资源
      最近更新 更多