在javascript回调中引用"this"

Zan*_*aes 6 javascript node.js

有些东西一直困扰着我在Javascript中进行面向对象编码的方式.当有回调时,我经常想引用最初调用该函数的对象,这导致我做这样的事情:

MyClass.prototype.doSomething = function(obj, callback) {
    var me = this; // ugh
    obj.loadSomething(function(err, result) {
        me.data = result; // ugh
        callback(null, me);
    });
}
Run Code Online (Sandbox Code Playgroud)

首先,总是创建额外的变量对我来说太过分了.此外,我不得不怀疑它是否可能最终导致问题(循环引用?un-GCd对象?)通过将"me"变量传递回回调.

有没有更好的方法来解决这个问题?这种做法是邪恶的吗?

mil*_*ose 8

Function.bind()是为了什么:

MyClass.prototype.doSomething = function(obj, callback) {
    obj.loadSomething((function(err, result) {
        this.data = result;
        callback(null, this);
    }).bind(this));
}
Run Code Online (Sandbox Code Playgroud)

  • 可能想把'我'改成'这个' (3认同)

she*_*man 7

AFAIK,你正在做的是这种事情的公认模式,并没有引起任何问题.很多人使用"self"或"that"作为存储引用 - 如果你来自python背景,"self"可以更直观.

  • 我喜欢"自我".然而**也是*window.self` ..虽然我从来没有对这个问题感到困惑. (2认同)