![](/img/trans.png)
[英]How to access class member variables inside an event handler defined in a class prototype - Javascript
[英]Setting member variables of Prototype class in Nodejs
var MyClass = (function() {
function MyClass(m) {
this.m = m;
}
MyClass.prototype.temp = function() {
process.nextTick(function() {
console.log(m);
});
}
});
for (var i=0; i<3; i++) {
var t = new MyClass(i);
}
上面的代碼總是覆蓋在其他實例中初始化的私有變量。 它顯示2,2,2而不是0,1,2。成員變量m
是否以這種方式設置?
然而它沒有process.nextTick
工作正常。 任何想法?
您的代碼示例不完整,但我相信您的真實代碼仍會遇到以下問題:
process.nextTick(function() {
console.log(m); //where does the m variable came from?
});
將您的代碼更改為:
process.nextTick((function() {
console.log(this.m);
}).bind(this));
bind
用於確保nextTick
回調中的this
值是當前的MyClass
實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.