我有这样的代码:
{
// other functions...
myFunction: function( item, options, callback ) {
var self = this;
// Both item and options variables are accessible here.
try {
var content = this.getContent( item );
} catch(ex) {
// Exception handling here....
}
editor.saveContent( content, function() {
// OPTIONS IS UNDEFINED HERE!
// ITEM IS UNDEFINED HERE!
// Callback, instead, is accessible!
if ( callback ) { callback() };
});
}
}
问题是在saveContent
回调中,我可以访问callback
变量,同时尝试访问item
,options
和content
回调不成功!那是为什么?
答案 0 :(得分:0)
您应该将您感兴趣的变量提供给回调函数,如下所示:
editor.saveContent( content, function() {
if ( callback ) { callback(item, options) };
});
通过javascript closure,item
和options
变量在saveContent
函数中可用。
创建fiddle以演示(请参阅控制台日志)。
答案 1 :(得分:0)
您发布的代码应该可以正常运行。但如果那确实不起作用,那么尝试编写这样的代码:
JavaPairRDD<ImmutableBytesWritable, Result> hBaseRDD = ctx.newAPIHadoopRDD(
conf,
TextInputFormat.class,,
org.apache.hadoop.hbase.io.ImmutableBytesWritable.class,
org.apache.hadoop.hbase.client.Result.class);
您已在try-catch块中写入{
// other functions...
myFunction: function( item, options, callback ) {
var self = this;
// Store the reference in "this"
self.item = item;
self.options = options;
self.callback = callback;
// Both item and options variables are accessible here.
try {
self.content = this.getContent( item );
} catch(ex) {
// Exception handling here....
}
editor.saveContent( self.content, function() {
// Use them here
console.log(this.item, this.options, this.content);
// Callback, instead, is accessible!
if ( this.callback ) { this.callback() };
}.bind(self));
}
}
。所以无论如何都无法在try-catch块之外访问它。
答案 2 :(得分:-2)
editor.saveContent.call(this,content, function(){
//can access any variable defined in its parent scope
});