javascript - var self = 这个?

标签 javascript jquery scope closures

使用实例方法作为事件处理程序的回调将 this 的范围从 "My instance" 更改为 "Whatever just called the callback" .所以我的代码是这样的

function MyObject() {
  this.doSomething = function() {
    ...
  }

  var self = this
  $('#foobar').bind('click', function(){
    self.doSomethng()
    // this.doSomething() would not work here
  })
}

它有效,但这是最好的方法吗?我觉得很奇怪。

最佳答案

这个问题不是特定于 jQuery,而是特定于 JavaScript。核心问题是如何在嵌入式函数中“引导”变量。这是一个例子:

var abc = 1; // we want to use this variable in embedded functions

function xyz(){
  console.log(abc); // it is available here!
  function qwe(){
    console.log(abc); // it is available here too!
  }
  ...
};

这种技术依赖于使用闭包。但它不适用于 this 因为 this 是一个伪变量,可能会在范围之间动态变化:

// we want to use "this" variable in embedded functions

function xyz(){
  // "this" is different here!
  console.log(this); // not what we wanted!
  function qwe(){
    // "this" is different here too!
    console.log(this); // not what we wanted!
  }
  ...
};

我们能做什么?将其分配给某个变量并通过别名使用它:

var abc = this; // we want to use this variable in embedded functions

function xyz(){
  // "this" is different here! --- but we don't care!
  console.log(abc); // now it is the right object!
  function qwe(){
    // "this" is different here too! --- but we don't care!
    console.log(abc); // it is the right object here too!
  }
  ...
};

this 在这方面不是唯一的:arguments 是另一个应该以相同方式处理的伪变量——通过别名。

关于javascript - var self = 这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/337878/

相关文章:

javascript - Browserify、minifyify、条件编译

javascript - 视频播放器源码更新

javascript - jQuery 从其他未选择的列表中选择一个 eq 目标

python - lambda 中的变量作用域

javascript - jsFiddle 自定义 DTD

javascript - TypeORM:使用自定义属性查询多对多

javascript - 在 jqGrid 上添加自定义按钮以打开其他一些 URL

javascript - jQuery 加载后初始化 slider

javascript - JS 变量作用域

javascript - Javascript 中的 block 作用域、函数作用域和局部作用域