Javascript 使用带参数的setTimeout而不是内联函数定义时可能需要注意的事项?
案例2中可能存在哪些警告 案例1:Javascript 使用带参数的setTimeout而不是内联函数定义时可能需要注意的事项?,javascript,syntax,arguments,settimeout,Javascript,Syntax,Arguments,Settimeout,案例2中可能存在哪些警告 案例1: setTimeout(function(){el.removeEventListener('click',console.log,true)},100) 和案例2: setTimeout(el.removeEventListener,100,'click',console.log,true) 我真的觉得case-1语法很难看,这就是问题所在 您的“案例2”将失败,因为调用removeEventListener时没有任何特定的this值,因此当this设置为el
setTimeout(function(){el.removeEventListener('click',console.log,true)},100)
和案例2:
setTimeout(el.removeEventListener,100,'click',console.log,true)
我真的觉得case-1语法很难看,这就是问题所在
您的“案例2”将失败,因为调用removeEventListener
时没有任何特定的this
值,因此当this
设置为el
时不会调用它。有效的比较是:
案例1:
setTimeout(function(){ el.removeEventListener('click', console.log, true) }, 100 )
案例2:
setTimeout(el.removeEventListener.bind(el), 100, 'click', console.log, true)
// ------------------------------^^^^^^^^^
你用什么取决于你想做什么
在那种特定的情况下,如果您处理了这个
问题,那么您使用哪种方法无关紧要。但请考虑:
var x = function() { /* do something */};
el.addEventListener("click", x, false);
setTimeout(function() { el.removeEventListener("click", x, true); }, 100);
x = function() { /* do something else */};
// ...
removeEventListener
调用将失败,因为从计时器回调运行时起,x
不再引用已连接的函数(它引用不同的函数)。但您首选的语法是:
var x = function() { /* do something */};
el.addEventListener("click", x, false);
setTimeout(el.removeEventListener.bind(el), 100, "click", x, true);
x = function() { /* do something else */};
// ...
…将起作用,因为x
是在进行setTimeout
调用时计算的,而不是稍后,因此它引用了正确的函数
有时您需要x
的值,在这种情况下,您可以使用“case1”表单。当您希望立即对x
进行评估时,“案例2”是您希望使用的表单
旁注:使用
true
作为addEventListener
/removeEventListener
的第三个参数相对较少。它为事件的捕获阶段而不是更常见的冒泡阶段钩住(并解开)处理程序。@certainperformance它是故意这样提的,这样人们就不会偏离主要问题,但因为你太具体了,我改变了问题。他不是“太具体”。一个例子应该很简单,是的,但这是有效的。