获取一个asynchronous父函数的参数
我有这个:
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
传递callback没有path的文件名。 所以我希望它得到父函数参数_file
。 我以为我可以使用.call
,但如何在callback中做到这一点?
有很多的可能性,一个是使用Function.prototype.bind
,如果你不需要在callback中访问原来的this value
:
fs.watch( _file, change.bind({_file: _file});
这样你可以像访问_file
一样
this._file;
在你的callback方法中。
谨慎的一句话:请注意,您在callback方法中使用另一个匿名函数来callbackfiles.clients
。 this
没有引用相同的值。 所以如果你想访问我们新近通过的this
引用,你需要调用另一个.bind()
调用,或者只是在本地variables中存储一个外部引用。