【问题标题】:Callbacks, anonymous functions and context回调、匿名函数和上下文
【发布时间】:2013-01-31 22:12:54
【问题描述】:

这段代码有什么区别:

$('.percentage_field').change(function() {
    update_percentage();
});
$('.inspect1').change(function(){
    show_hide_targets();
});

还有这段代码:

$('.percentage_field').change(
    update_percentage
);

$('.inspect1').change(
    show_hide_targets
);

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    当为响应事件而运行回调时,函数内部的this 被设置为作为事件目标的 DOM 元素。

    在您的第一个示例中,匿名函数获取目标元素的this,但this 没有转发到内部函数调用。相反,内部函数使用this according to how it is invoked 运行。 (这里,它是一个直接的“原始”调用(即,不作为成员函数调用),因此它在非脚本模式下以等于windowthis 运行。)

    在您的第二个示例中,函数update_percentageshow_hide_targets 直接获取目标元素的this

    考虑an example

    function sayThis() { alert(this); }
    someElem.addEventListener("click", function() { sayThis() });
    someElem.addEventListener("click", sayThis);
    someElem.addEventListener("click", function() { sayThis.call(this) });
    

    第一个将提醒window(或在严格模式下undefined);第二个将提醒监听器触发的元素。第三个监听器使用匿名函数,但它使用.call(this) 调用内部函数,将原始this 转发给内部函数。

    【讨论】:

      猜你喜欢
      • 2014-05-05
      • 1970-01-01
      • 2011-06-21
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多