jQuery - 插件选项默认extend()

Pie*_*NAY 7 javascript jquery jquery-plugins

按照良好的jQuery插件/创作说明,我有一个小问题

(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);
Run Code Online (Sandbox Code Playgroud)

如果我做

>>> $('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 ]
Run Code Online (Sandbox Code Playgroud)

为什么我var1没有被覆盖?

m90*_*m90 20

你混淆了你的参数的顺序$.extend(目标应该是第一个),它应该是:

settings = $.extend(settings, options);
Run Code Online (Sandbox Code Playgroud)

看到这个小提琴文档$.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

};
Run Code Online (Sandbox Code Playgroud)