我正在编写下面的代码,一次解析一个站点 API,然后告诉事件队列它已准备好等待下一个要解析的对象。我遇到了一些问题,因为我对 javascript 范围界定还很陌生,并且想从 SiteParser 发出或调用 emitForNext 函数。我似乎无法将 emitForNext 带入错误回调的范围。
function SiteParser(){
this.emitForNext = function (message) {
this.emit("next", message);
};
this.pullJSON = function (path, processJSON) { //processJSON is a callback function
var options = {
host: 'www.site.com',
port: 80,
path: path
}
//console.log("... processing "+path);
//pulls the entire json request via chunks
http.get(options, function (res) {
var resJSON = ''; //stores the comment JSON stream given in the res
res.on('data', function (chunk) {
resJSON+=chunk;
});
res.on('end', function () {
var obJSON = (JSON.parse(resJSON));
if (obJSON.hasOwnProperty("error")){
console.log(obJSON);
console.log('... ', path, ' does not exist');
//
//NEED A NEXT EVENT EMMITER HERE NEED TO FIGURE OUT SCOPE
//
//
} else {
processJSON(obJSON); //call the callback function
}
}) ;
}).on('error', function (e) {
emitForNext("got error: " + e.message);
});
};
}
最佳答案
JavaScript 有函数作用域,如果你用 var 关键字声明一个变量,它将是当前函数的局部变量。当你访问一个变量时,它会查看由当前函数、它的父函数……组成的作用域链。尝试:
function one() {
var foo = 'foo';
function two() {
console.log(foo) // undefined. I'll explain this
var foo = 'bar';
console.log(foo) // bar
}
two()
console.log(foo) // foo
}
one()
大多数时候我们在函数的开头定义变量,因为在函数体中定义的变量会被提升。基本上,这意味着它在整个函数中可用,甚至在它被定义之前,但在这种情况下它的值为 undefined
。
例如,如果 undefined variable ,我们通常会得到一个ReferenceError
,但在下面的代码片段中,两个console.log()
都只是打印undefined
.
function foo() {
console.log(bar);
if (0) {
var bar = 'bar';
}
console.log(bar);
}
因此,一个常见的做法是,当您编写长函数时,您将 this 映射到 self。
function SiteParser() {
var self = this;
// ...
.error('error', function(err) {
self.emitForNext("got " + err.message);
})
}
你不应该把你所有的方法都写在构造函数中,它只在我们需要隐私的时候才有用,但在这种情况下你最好使用原型(prototype)。
把这些放在一起,我会写:
var SiteParser = function() {};
SiteParser.prototype.emitForNext = function(message) {
this.emit("next", message);
};
SiteParser.prototype.pullJSON = function(path, processJSON) {
var self = this,
options = {
host: 'www.site.com',
port: 80,
path: path
};
http.get(options, function(res) {
// ...
}).on('error', function (e) {
self.emitForNext("got error: " + e.message);
});
};
关于events - 我如何从 Node.js 中的嵌套函数内部发送到 eventListener(javascript 范围问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9631989/