nodejs – 哪个“这个”是这个?
所以这是一个尴尬的问题,但我正在学习NodeJS,我有一个问题。 在Java中,当我从一个对象中调用一个方法时, this
实例保持不变(如本例中)。
private Test inst; public Test() { inst = this; this.myFunction(); } private void myFunction() { System.out.println(inst == this); }
这返回true(理论上,这是代码我的头顶)。 但是,在NodeJS中,当我尝试做类似的事情时,它失败了。
var MyObject = function () { this.other = new OtherObject(); this.other.on("error", this.onError); console.log(this); //This returns the MyObject object } MyObject.prototype.onError = function (e) { console.log(this); //This returns the OtherObject object, where I thought it would return the MyObject object. }
我的问题是为什么是这样,如果这是我的部分做的不正确,我怎么可能从onError方法正确引用MyObject实例中的其他variables?
在JavaScript中,“方法”只是函数的一部分。
如果你这样做
var obj = new MyObject(); obj.onError();
onError中的this将是obj对象(因为它是从中调用的对象)
相反,如果您将this.onError传递给EventEmitter,它将使用EventEmitter(OtherObject)调用该函数。
为了避免这个问题,使用一个非常规的函数。
var MyObject = function () { var self = this; this.other = new OtherObject(); this.other.on("error", function (e) { self.onError(e); }); }
通过这种方式,您可以将其绑定回您期望的对象
有更简单的方法 – 你可以使用绑定function。
var EventEmitter = require('events').EventEmitter; var MyObject = function () { this.other = new EventEmitter(); this.other.on("error", this.onError.bind(this)); console.log(1, this instanceof MyObject); // 1, true }; MyObject.prototype.onError = function (e) { console.log(2, this instanceof MyObject); // 2, true }; MyObject.prototype.callError = function (e) { console.log(3, this instanceof MyObject); // 3, true this.other.emit('error', e); }; var mo = new MyObject(); mo.callError(new Error(1));
演示