【问题标题】:What happens to 'this' between two calls of .each()?两次调用 .each() 之间的“this”会发生什么?
【发布时间】:2019-07-31 13:53:08
【问题描述】:

FF 68.0.1 中的 GM 脚本中的以下代码:

let input = $( 'input#id' );

input.each( function(){console.debug(this)} );
input.each( debugn(this) );

function debugn( message ) {
  console.debug(message)
}

先打印:

<input id="id" ...>

正如预期的那样:

Sandbox { browser: {...

即使内部迭代器在第一次调用时被使用并且在第二次调用时没有初始化(尽管.each() 没有提到这种行为)它不应该打印Sandbox 对象,而只是不调用debugn(...) ,不应该吗?

【问题讨论】:

    标签: jquery firefox console each greasemonkey-4


    【解决方案1】:

    这与您调用 .each 方法两次这一事实无关,而是您每次调用它的方式。

    第一次调用匿名函数时,该函数又调用 console.debug 方法并将 this 作为参数传递。

    第二次,您将 debugn 函数作为参数传递给 each 函数,该函数又调用 console.debug 方法,但由于您将函数直接作为每个函数的参数传递,因此上下文发生了变化。

    简短的回答:您首先执行的方式是 Jquery 希望您执行的方式。如果你有一个要调用的命名函数,只需在匿名函数中调用它,就像你第一次做的那样

    input.each( function(){
      debugn(this)
    } );
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 2023-03-21
      • 2010-12-02
      • 2014-04-04
      • 2012-10-11
      • 2015-02-13
      相关资源
      最近更新 更多