获取异步父函数的参数

时间:2012-04-11 15:17:05

标签: javascript node.js

我有这个:

function change( event, file ) {
  console.log( "filename", file );
  //It should be '_file', not 'file'.
  files.clients( file, function( clientOfFile ) {
    console.log( "for client:", clientOfFile );
    io.sockets.socket( clientOfFile ).emit( "change" );
  } );
}

client.on( "watch", function( file ) {
   _file = base + file; //filename with path
   files.add( _file, client.id );
   fs.watch( _file, change );
} );

fs.watch传递回调没有路径的文件名。所以我想让它获得父函数参数_file。我以为我可以使用.call,但如何在回调中使用它?

1 个答案:

答案 0 :(得分:3)

如果您不需要访问回调中的原始Function.prototype.bind,则可以使用this value,这是很有可能的事情:

fs.watch( _file, change.bind({_file: _file});

这样您就可以像

那样访问_file
this._file;

在你的回调方法中。


提醒一句:请注意您在回调方法中使用另一个匿名函数来回调files.clientsthis未在其中引用相同的值。因此,如果您想在那里访问我们新传递的this引用,您需要调用另一个.bind()调用,或者只在本地变量中存储this的外部引用。