保持对“this”的引用。在Javascript中使用回调和闭包 [英] Maintaining the reference to "this" in Javascript when using callbacks and closures

查看:77
本文介绍了保持对“this”的引用。在Javascript中使用回调和闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己将this分配给变量,因此我可以在回调和闭包中轻松使用它。

I find myself assigning "this" to a variable so I can easily use it in callbacks and closures.

这是不好的做法吗?有没有更好的方式回顾原始函数?

Is this bad practice? Is there a better way of referring back to the original function?

这是一个典型的例子。

User.prototype.edit = function(req, res) {

  var self = this,
      db = this.app.db;

  db.User.findById('ABCD', function(err, user)) {

    // I cannot use this.foo(user)
    self.foo(user);
  });
};

User.prototype.foo = function(user) {

};

您通常使用这种方法还是找到了更清洁的解决方案?

Do you normally use this approach or have you found a cleaner solution?

推荐答案

在回调中有三种主要的方法来处理这个

There are three main ways to deal with this in callbacks:

这个新变量的两个最常见的名称是 自我。我个人更喜欢使用 ,因为浏览器有一个名为self的全局窗口属性,如果我遮住它,我的linter会抱怨。

The two most common names for this new variable are that and self. I personally prefer using that because browsers have a global window property called self and my linter complains if I shadow it.

function edit(req, res) {
    var that = this,
    db.User.findById('ABCD', function(err, user){
        that.foo(user);
    });
};

这种方法的一个优点是一旦代码转换为使用 你可以根据需要添加尽可能多的内部回调,并且由于词法范围,它们都可以无缝地工作。另一个优点是它非常简单,甚至可以在古老的浏览器上使用。

One advantage of this approach is that once the code is converted to using that you can add as many inner callbacks as you want and they will all seamlessly work due to lexical scoping. Another advantage is that its very simple and will work even on ancient browsers.

Javascript函数有 .bind() 方法,可让您创建具有固定 this 。

Javascript functions have a .bind() method that lets you create a version of them that has a fixed this.

function edit(req, res) {
    db.User.findById('ABCD', (function(err, user){
        this.foo(user);
    }).bind(this));
};

在处理时, bind方法特别适用于一个回调,其中必须添加一个包装函数会更详细:

When it comes to handling this, the bind method is specially useful for one-of callbacks where having to add a wrapper function would be more verbose:

setTimeout(this.someMethod.bind(this), 500);

var that = this;
setTimeout(function(){ that.doSomething() }, 500);

bind 的主要缺点是,如果你有嵌套的回调,那么你还需要在它们上调用 bind 。此外, IE< = 8和其他一些旧浏览器,不要原生实现 bind 方法,因此您可能需要使用某种填充库如果你仍然需要支持他们。

The main disadvantage of bind is that if you have nested callbacks then you also need to call bind on them. Additionally, IE <= 8 and some other old browsers, don't natively implement the bind method so you might need to use some sort of shimming library if you still have to support them.

控制函数参数的更原始的方法Javascript,包括 this ,是 .call() .apply() 方法。它们允许您使用任何对象调用函数作为 this 以及任何值作为其参数。 apply 对于实现可变参数函数特别有用,因为它接收参数列表作为数组。

The more primitive ways to control function parameters in Javascript, including the this, are the .call() and .apply() methods. They let you call a function with whatever object as their this and whatever values as its parameters. apply is specially useful for implementing variadic functions, since it receives the argument list as an array.

例如,这是bind的一个版本,它接收绑定为字符串的方法。这让我们只记下这个而不是两次。

For example, here is a version of bind that receives the method to bind as a string. This lets us write down the this only once instead of twice.

function myBind(obj, funcname){
     return function(/**/){
         return obj[funcname].apply(obj, arguments);
     };
}

setTimeout(myBind(this, 'someMethod'), 500);

这篇关于保持对“this”的引用。在Javascript中使用回调和闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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