var self = 这个? [英] var self = this?

查看:29
本文介绍了var self = 这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用实例方法作为事件处理程序的回调将this 的范围从我的实例" 更改为任何刚刚调用的回调".所以我的代码看起来像这样

Using instance methods as callbacks for event handlers changes the scope of this from "My instance" to "Whatever just called the callback". So my code looks like this

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

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

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

It works, but is that the best way to do it? It looks strange to me.

推荐答案

这个问题并非特定于 jQuery,而是特定于一般的 JavaScript.核心问题是如何在嵌入式函数中引导"变量.这是示例:

This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:

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 是一个伪变量,可能会在作用域之间动态变化:

This technique relies on using a closure. But it doesn't work with this because this is a pseudo variable that may change from scope to scope dynamically:

// 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!
  }
  ...
};

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

What can we do? Assign it to some variable and use it through the alias:

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 是另一个应该以相同方式处理的伪变量 —通过别名.

this is not unique in this respect: arguments is the other pseudo variable that should be treated the same way — by aliasing.

这篇关于var self = 这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆