js對象深潛拷貝(從requirejs中摳出來的)

來源:互聯網
上載者:User

標籤:

 1 var op = Object.prototype, 2     ostring = op.toString, 3     hasOwn = op.hasOwnProperty; 4  5 function isFunction(it) { 6     return ostring.call(it) === ‘[object Function]‘; 7 }; 8  9 function isArray(it) {10     return ostring.call(it) === ‘[object Array]‘;11 };12 function hasProp(obj, prop) {13     return hasOwn.call(obj, prop);14 };15 function eachProp(obj, func) {16     var prop;17     for (prop in obj) {18         if (hasProp(obj, prop)) {19             if (func(obj[prop], prop)) {20                 break;21             }22         }23     }24 };25 /**26  * Simple function to mix in properties from source into target,27  * but only if target does not already have a property of the same name.28  *29  * @param {target} 目標對象30  * @param {source} 來源物件31  * @param {force} 是否強制覆蓋目標對象已有的屬性32  * @param {deepStringMixin} 是否深拷貝遞迴操作33  *34  * @returns {target}35  */36 function mixin(target, source, force, deepStringMixin) {37     if (source) {38         eachProp(source, function (value, prop) {39             if (force || !hasProp(target, prop)) {40                 if (deepStringMixin && typeof value === ‘object‘ && value &&41                     !isArray(value) && !isFunction(value) &&42                     !(value instanceof RegExp)) {43 44                     if (!target[prop]) {45                         target[prop] = {};46                     }47                     mixin(target[prop], value, force, deepStringMixin);48                 } else {49                     target[prop] = value;50                 }51             }52         });53     }54     return target;55 };56 57 58 調用:59 var obj = {60     name:‘Tom‘,61     age:19,62     children:{63         name:‘Jack‘,64         age:3065     }66 };67 var obj2 = mixin({},obj,false,true);68 obj.children.name=‘Marry‘;69 console.log(obj2);

 

js對象深潛拷貝(從requirejs中摳出來的)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.