如何在匿名javascript中调用该函数? (TinyMce示例)

时间:2010-03-25 13:41:28

标签: javascript tinymce this closures

如何在该方法中调用test()?有可能吗?

(function() {

    tinymce.create('tinymce.plugins.WrImagerPlugin', {

        init : function(editor, url) { 

            editor.addCommand('mceWrImagerLink', function() {
                //--> how can i refer to test() here?
            });
        },
        test: function () {alert('test');}
        }
    });

    tinymce.PluginManager.add('wr_imager', tinymce.plugins.WrImagerPlugin);
})();

2 个答案:

答案 0 :(得分:5)

您可以将test作为常规函数并将其指定给对象,如下所示:

(function() {
    function test() { alert('test'); }

    tinymce.create('tinymce.plugins.WrImagerPlugin', {
        init : function(editor, url) { 
            editor.addCommand('mceWrImagerLink', function() {
                test();
            });
        },
        test: test
    });

    tinymce.PluginManager.add('wr_imager', tinymce.plugins.WrImagerPlugin);
})();

或者,您可以保留对该对象的引用:

(function() {
    var wrImaergPlugin = {    
        init : function(editor, url) { 
            editor.addCommand('mceWrImagerLink', function() {
                wrImagerPlugin.test();
            });
        },
        test: function() { alert('test'); }
    }

    tinymce.create('tinymce.plugins.WrImagerPlugin', wrImagerPlugin);
    tinymce.PluginManager.add('wr_imager', tinymce.plugins.WrImagerPlugin);
})();

最后,在这种特定情况下,您应该只需致电tinymce.plugins.WrImagerPlugin.test()

答案 1 :(得分:1)

您还可以在this关闭的init方法中保留对addCommand的引用:

(function() {

tinymce.create('tinymce.plugins.WrImagerPlugin', {

    init : function(editor, url) { 
        var me = this;
        editor.addCommand('mceWrImagerLink', function() {
            //--> how can i refer to test() here?
            me.test();
        });
    },
    test: function () {alert('test');}
    }
});

tinymce.PluginManager.add('wr_imager', tinymce.plugins.WrImagerPlugin);

})();