在JavaScriptcallback中引用“this”

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

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

首先,创造额外的variables似乎…对我来说太过分了。 此外,我不得不怀疑是否可能通过将“me”variables传回给callback来导致问题(循环引用?un-GCd对象?)。

有没有更好的方法去做这件事? 这种做法是邪恶的吗?

这是Function.bind()的用途:

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

AFAIK,你在做什么是这种事情的接受模式,并没有引起任何问题。 很多人使用“self”或“that”作为存储引用 – 如果你来自python背景,“self”可以更直观。

这是JavaScript的正常行为。 这个上下文已经改变了loadSomething对象,callback的原因是捕获像你的variables一样的闭包引用。

你可以将它绑定到内部函数的范围

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

这是我看到处理它最常见的方式,我通常使用var self = this;但它只是一个名字。 即使它是一个额外的variables,考虑到JavaScript的开销和事实,它不重复的对象,它真的不会影响性能。