私はjQueryプラグインを作成していて、特定の関数のスコープによって定期的に混乱しています(jSを使用する場合の従来のように)。
簡単な例が役立つはずです:
(function ( $ ) {
var methods = {
init: function ( options ) {
var settings = $.extend ({
a: 100,
b: 200
}, options);
return this.each(function(){
var $this = $(this);
var return_value = $this.plugintest("method_1", settings);
$this.plugintest("method_2", settings, return_value);
});
},
method_1 : function ( settings ) {
var method_1_value_1 = settings.a * 10,
method_1_value_2 = settings.a * 20;
return method_1_value_1;
},
method_2 : function ( settings, old_return_value ) {
// WHAT IF I WANT BOTH method_1_value_1 AND method_1_value_2 in here?
}
};
$.fn.plugintest = function (method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call ( arguments, 1 ) );
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist in jQuery.robottest' );
}
};
}) (jQuery);
method_2を参照してください。method_1で作成した値にアクセスしたいのですが、返すことができるのは1つの値だけです。ある種のグローバル変数を作成する必要がありますか?これを行うための「最良の」方法は何ですか?