如何在jQuery中创建适当的闭包?

n13*_*313 3 javascript jquery closures

这是我的代码示例:

var bar = function() {

  this.baz = function() {
    this.input = $('.input');
    this.input.bind("keydown keyup focus blur change", this.foo);
  }

  this.foo = function(event){
    console.log(this);
  }

}
Run Code Online (Sandbox Code Playgroud)

点击我的输入input显然是在控制台中.我怎样才能获得barthis呢?

CMS*_*CMS 5

这是因为绑定事件时,使用触发事件的DOM元素的上下文调用事件处理函数,this关键字表示DOM元素.

要获得"bar",您应该存储对外部闭包的引用:

var bar = function() {
  var self = this;

  this.baz = function() {
    this.input = $('.input');
    this.input.bind("keydown keyup focus blur change", this.foo);
  }

  this.foo = function(event){
    console.log(this); // the input
    console.log(self); // the bar scope
  }
};
Run Code Online (Sandbox Code Playgroud)

注意:如果没有new操作符调用bar函数,this将是window对象baz并且foo将成为全局变量,小心!

但是我认为你的代码可以简化:

var bar = {
  baz: function() {
    var input = $('.input');
    input.bind("keydown keyup focus blur change", this.foo);
  },

  foo: function(event){
    console.log(this); // the input
    console.log(bar); // reference to the bar object
  }
};
Run Code Online (Sandbox Code Playgroud)

  • 是的,但请注意,如果闭包是自动执行的,`baz`和`foo`将变为全局,因为`this`将成为窗口对象. (2认同)