$.extend()

// merge two object, modifying the first;
var object1={
apple:0,
banana:{weight:14,price:233},
cherry:97
};
var object2={
banana:{price:333},
cherry:38
};
jquery.extend(object1,object2);
//result:
  object1={apple:0,banana{price:333},cherry:38}
//Example: Merge two objects recursively, modifying the first
  var object1 = {
    apple: 0,
    banana: {weight: 52, price: 100},
    cherry: 97
  };
   var object2 = {
    banana: {price: 200},
    durian: 100
  };
  
  $.extend(true, object1, object2);
//result:
object1 === {apple: 0, banana: {weight: 52, price: 200}, cherry: 97, duria
//Example: Merge defaults and options, //without modifying the defaults. This is a common plugin development pattern.

 //target的参数要传递一个空对象,因为target的值最后要改变 


 var empty = {};

var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = $.extend(empty, defaults, options);
//result: settings == { validate: true, limit: 5, name: "bar"     empty == { validate: true, limit: 5, name: "bar"}


 jquery.extend()是编写插件是最常用到的工具函数来处理options;

 下面是fancybox插件的来处理options;


 例如: settings=jquery.extend({},$.fn.fancybox.defaults,settings);


  上面的代码target是个空对象,这样把默认设置defaults作为第一个对象,将用户传入的设置setting合并到defaults上,

  然后将合并后的结果复制给target并将返回值返回。


  下面一个例子: 


  var defaults = { validate: false, limit: 5, name: "foo" };
  var options = { validate: true, name: "bar" };


  var setting=$.extend(defaults,options);


  上面的代码将defaults作为target的参数,最后和setting的值一样但是defaults的值被改变了,而插件的默认值都是固定,所以使用时注意target的参数的用法。


你可能感兴趣的:(jquery,apple)