我在寫一個jQuery插件,並且經常被某些函數的範圍所困惑(就像使用jS時的傳統一樣)。Structring jQuery插件
簡單例子應該有所幫助:
(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個值 - 我應該創建某種全局變量嗎?做這個的最好方式是什麼?
你可以從你'method_1'與每個值屬性返回的對象。 –