简体   繁体   English

为什么setTimeout无法识别函数名称?

[英]Why doesn't setTimeout recognize function name?

(function( $ ){

   $.fn.hash = function(){

   function activate()
   {
      setTimeout('checkHash()', 100);
   }

   activate();

   var previousHashTag = location.hash;

   var previousHashProperty = '';

   function checkHash()
   {
     if( previousHashTag !== location.hash )
     {
        $('body').trigger("hashchange", [ getHashObj() ]);
        previousHashTag = location.hash;
        setTimeout( "checkHash()", 200);
     }
     setTimeout( "checkHash()", 100);
   }

This is my hash plugin I'm trying to make. 这是我要制作的哈希插件。 I would like to call the activate() function when user loads the plugin. 当用户加载插件时,我想调用activate()函数。 The activate function would set a timeout to check for a hash every 100 miliseconds. activate函数将设置一个超时,以每100毫秒检查一次哈希。 How can I pull this off since checkHash is outside of the function in this object? 由于checkHash在此对象的函数之外,我该如何实现?

You are passing strings to setTimeout and evaluating them. 您正在将字符串传递给setTimeout并对其进行评估。 This breaks the normal scope. 这打破了正常范围。 Don't do that, pass functions instead. 不要这样做,而是传递函数。

setTimeout(checkHash, 100);

Now scope will be preserved, and you can access activate from checkHash and vice versa as they are declared in the same scope. 现在将保留作用域,并且您可以从checkHash访问activate ,反之亦然,因为它们在同一作用域中声明。

You are using string argument in setTimeout , which means that the code will be run in global object. 您在setTimeout中使用字符串参数,这意味着代码将在全局对象中运行。 As your called function is defined inside a closure of another function, you have to pass a reference 由于您的调用函数是在另一个函数的闭包中定义的,因此您必须传递一个引用

setTimeout(checkHash, 100);

or use anonymous function 或使用匿名功能

setTimeout(function(){
  checkHash();
});

You have to use the second approach when you want to pass any arguments to function called from setTimeout . 要将任何参数传递给从setTimeout调用的函数时,必须使用第二种方法。

setTimeout(function(){
  checkHash(arg);
});

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

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