回调丢失包含函数的范围

时间:2016-02-16 10:10:07

标签: javascript

我有这样的代码:

{
    // 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变量,同时尝试访问itemoptionscontent回调不成功!那是为什么?

3 个答案:

答案 0 :(得分:0)

您应该将您感兴趣的变量提供给回调函数,如下所示:

editor.saveContent( content, function() {
    if ( callback ) { callback(item, options) };
});

通过javascript closureitemoptions变量在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
});