获取异步父函数的参数

Get an argument of an asynchronous parent function

本文关键字:参数 函数 异步 获取      更新时间:2023-09-26

>我有这个:

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,但是如何在回调中做到这一点?

有很多可能性,一种是使用 Function.prototype.bind ,如果您不需要在回调中访问原始this value

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

这样您就可以访问_file例如

this._file;

在回调方法中。


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