jQuery的$ .proxy vs var self - 保存`this`上下文的常用方法

Ale*_*ley 5 jquery

保留上下文的常用方法是this什么?什么更快?你更喜欢什么?

  1. $ .proxy(...)

    $('a').on('click', $.proxy(function() {
        this.close();
    }, this));
    
    Run Code Online (Sandbox Code Playgroud)
  2. var self

    var self = this;
    
    $('a').on('click', function() {
        self.close();
    });
    
    Run Code Online (Sandbox Code Playgroud)

Den*_*ret 2

让我们从修复您的代码开始。你有一个无用的函数声明,你可以使用$.proxyas

$('a').on('click', $.proxy(this.close, this));
Run Code Online (Sandbox Code Playgroud)

现在,第二种解决方案基于self

  • 只需要基本的 JavaScript 知识
  • 不需要 jQuery
  • 更具可读性,特别是当您经常重用self变量时
  • 快得多

这可能就是它被更多使用的原因。

请注意,当您不必兼容 IE8 时,您可以使用bind

$('a').on('click', this.close.bind(this));
Run Code Online (Sandbox Code Playgroud)