(jquery| | Zepto). A small problem with extend

Source: Internet
Author: User

Recently has been engaged in mobile, but also because of their familiarity with jquery, coupled with zepto provided with the same API as jquery, so chose Zepto as the development framework.

Because it's mobile development, there are some ES5 new APIs, such as foreach, and here are some examples of the code I wrote:

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

I was naïve to think that foreach is like each of jquery, as long as my return value is false, it interrupts the loop, so the traversal code like this writes a lot (really lazy for each traversal to declare the variable AH)

After writing for a while I suddenly realized that the callback function of foreach could not interrupt the loop, so I hung a function on the Array.prototype and then ReplaceAll, perfect.

function (FN) {    varthis. length;      for (; i < Len; + +i)       {if (FN(thisfalse)          {break ;       }     } };

Until one day, I would like to do some optimization, considering that the client needs to save the JSON too large (do not cheat you, the maximum can go to 20M), stringify time is too much time, 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:

function (e) {  var data = e.data;   = json.stringify (data);   false);

Posmesage:

Worker.postmessage (data)

However, the console outputs the following error message:

Uncaught datacloneerror:failed to execute ' postMessage ' in ' Worker ': An object could not being cloned.

Pit Dad, this day kill why even a JSON can not copy, so, I began to look for reasons, let me find my json inside there is this thing:

Oh, my God, what the hell is this, this foreach came in, and I looked at the $.extend inside the editor (true, {}, obj) shivering there, and I couldn't help wondering if it was you. So, I looked at the source of the $.extend:

  functionExtend (target, source, deep) { for(Keyinchsource)if(Deep && (Isplainobject (source[key)) | |IsArray (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) {varDeep, args = Slice.call (arguments, 1)    if(typeoftarget = = ' Boolean ') { deep=Target Target=args.shift ()} Args.foreach (function(ARG) {Extend (target, ARG, deep)})returnTarget}

Oh, my God, this is a real thing. Go through the 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 to check how much time is not wasted. Tears

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

Jquery.extend = JQuery.fn.extend =function() {    varoptions, name, SRC, copy, Copyisarray, clone, Target= Arguments[0] | |{}, I= 1, Length=Arguments.length, deep=false; //Handle a deep copy situation    if(typeoftarget = = = "Boolean") { deep=Target; Target= Arguments[1] | | {}; //Skip the Boolean and the targeti = 2; }    //Handle Case If Target is a string or something (possible in deep copy)    if(typeofTarget!== "Object" &&!jquery.isfunction (target)) {Target= {}; }    //extend JQuery itself if only one argument is 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(Nameinchoptions) {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.isplainobject (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 themtarget[name] =jquery.extend (deep, clone, copy); //Don ' t bring in undefined values}Else if(Copy!==undefined) {target[name]=copy; }            }        }    }    //Return the Modified object    returntarget;};

The goods are also else if (copy!== undefined) {target[name] = copy; } on the account, my mother ah.

Finally forced to write a.

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

(jquery| | Zepto). A small problem with extend

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.