按照良好的
jQuery Plugins/Authoring指令,我有一个小问题
(function($){ // Default Settings var settings = { var1: 50,var2: 100 }; var methods = { init : function (options) { console.log(settings); settings = $.extend(options,settings); // Overwrite settings console.log(settings); return this; },other_func: function () { return this; } }; $.fn.my_plugin = 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 on jQuery.my_plugin'); } }; })(jQuery);
如果我做
>>> $('my_element').my_plugin({var3: 60}) Before Object { var2=100,var1=50} After Object { var3=60,var2=100,var1=50} [ my_element ] >>> $('my_element').my_plugin({var1: 60}) Before Object { var1=50,var2=100} After Object { var1=50,var2=100} [ my_element ]
为什么我的var1没有被覆盖?
解决方法
你混淆了$.extend中的参数顺序(目标应该是第一个),它应该是:
settings = $.extend(settings,options);
见@L_301_1@和docs for $.extend()
为避免混淆,您还可以使用以下默认值扩展您的设置:
methods.init = function(options){ var settings = $.extend({ key1: 'default value for key 1',key2: 'default value for key 2' },options); // <- if no / undefined options are passed extend will simply return the defaults //here goes the rest };