A little problem with $.extend _jquery

Source: Internet
Author: User
Tags extend

I've been working on the mobile side lately, and since I'm familiar with jquery, plus Zepto provides the same API as jquery, I chose Zepto as the development framework.

As a result of the mobile-side development, some ES5 new APIs, such as foreach, are also applied, and here are some examples of the code I wrote:

List.foreach (function (v) {return
 !! v;
})

I naively thought that foreach was like each of jquery's, so long as my return value was false, it would interrupt the loop, so the traversal code like this would have written a lot (really lazy to declare variables for each traversal).

After writing for a while, I suddenly discovered that foreach's callback function did not interrupt the loop, so I hung a function on the Array.prototype, then ReplaceAll, perfect.

 Array.prototype.foreach = function (fn) {
  var i = 0, len = this.length;

  for (; i < Len; ++i) {

    if (FN (this[i), i) = = False) {break
     ;}}}
 ;

Until one day, I want to do some optimization, considering the client needs to save the JSON too large (not fooled you, the maximum can go to 20M), stringify time is too time-consuming, will block the UI, so I use the worker in the background to open a thread, specifically used to stringify this JSON, Similar to this:

Copy Code code as follows:

AddEventListener ("Message", function (e) {
var data = E.data;
data = json.stringify (data);
PostMessage (data);
}, False);

Posmesage:

Copy Code code as follows:

Worker.postmessage (data)

However, the console prints the following error message:

Copy Code code as follows:

Uncaught datacloneerror:failed to execute ' postMessage '-' Worker ': An object could is not cloned.

Pit Dad, this day killed why not even a JSON copy, so, I began to look for the reason, let me find my json there is this thing:

God, what the hell is this, this foreach came in, I looked at the editor inside the $.extend (true, {}, obj) is shivering in there, I can not help but doubt that you are not in the mischief. So, I looked at the $.extend source:

 function extend (target, source, deep) {for
  (key in Source)
   if (Deep && (Isplainobject (source[key)) | | isA Rray (Source[key])) {
    if (Isplainobject (Source[key)) &&!isplainobject (Target[key]))
     Target[key] = { }
    if (IsArray (Source[key]) &&!isarray (target[key))
     target[key] = []
    extend (target[key), source  [key], deep)
   }
   else if (Source[key]!== undefined) target[key] = Source[key]
 }

 //Copy all but undefined Properties from one or more
 //objects to the ' target ' object.
 $.extend = function (target) {
  var deep, args = Slice.call (arguments, 1)
  if (typeof target = = ' Boolean ') {
   de EP = target
   target = Args.shift ()
  }
  Args.foreach (function (ARG) {Extend (target, ARG, deep)})
  return Target
 }

Oh, my God, this is really the goods in the AH, traversal array with for...in ... Forget it, but else if (Source[key]!== undefined) target[key] = Source[key The conditions here can be serious ah, add a hasownproperty check will not waste much time. Tears

After being Zepto pit, I immediately went to find jquery complaints, I hope it can comfort me, did not think:

Jquery.extend = JQuery.fn.extend = function () {var options, name, SRC, copy, Copyisarray, clone, target = argument S[0] | |

  {}, I = 1, length = arguments.length, deep = false;
    Handle a deep copy situation if (typeof target = = "Boolean") {deep = target; target = Arguments[1] | |
    {};
  Skip the Boolean and the target i = 2; //Handle case when the target is a string or something (possible in deep copy) if (typeof target!== "Object" &AMP;&A
  MP;!jquery.isfunction (target)) {target = {};
    }//Extend JQuery itself if only one argument are passed if (length = = i) {target = this;
  I.;  for (; i < length; i++) {//only deal with non-null/undefined values if (options = arguments[i])!=
        NULL) {//Extend the Base object for (name in options) {src = target[name];

        copy = options[name];
         Prevent never-ending loop if (target = = copy) { Continue }//Recurse If we re merging plain objects or arrays if (deep && copy && (jquery.ispla Inobject (copy) | | (Copyisarray = Jquery.isarray (copy))
            {if (copyisarray) {Copyisarray = false; clone = src && jquery.isarray (src)?

          SRC: [];
          else {clone = src && jquery.isplainobject (src)? src: {};

        }//Never Move original objects, clone them target[name] = Jquery.extend (deep, clone, copy);
        Don ' t bring in undefined values} else if (copy!== undefined) {target[name] = copy;
}}//Return the modified object return target;

 };

The goods are also else if (copy!== undefined) {target[name] = copy;

Finally compelled to write one himself.

Summary: When you want to use $.extend, do not easily hang on Array.prototype and object.prototype your custom attributes and methods, otherwise, you may have to find a bug.

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.