zoukankan      html  css  js  c++  java
  • javascript 对象的复制

    1.  jQuery has a method that can be used to deep-clone objects, the$.extend() function. Let’s take a look at how it can be used:

    var bob = {
        name: "Bob",
        age: 32
    };
     
    var bill = $.extend(true, {}, bob);
    bill.name = "Bill";
     
    console.log(bob);
    console.log(bill);
    

    注意:Pretty handy, eh? This method is a little slower than the JSON exploit, but that shouldn’t really be a problem when you’re only doing a few clones. If you’re doing hundreds or thousands of clones, it might be time to think about the JSON exploit or another solution.

    2.   A clever exploit of the JSON library to deep-clone objects

    We can exploit the JSON library for a rather fast way of deep-cloning objects. Check it out:

    var bob = {
        name: "Bob",
        age: 32
    };
     
    var bill = (JSON.parse(JSON.stringify(bob)));
    bill.name = "Bill";
     
    console.log(bob);
    console.log(bill);
    

    3.  tipJS中的一个方法,也不错 ,不过我自己还没完全理解这个方法的独到之处(或者说这个方法的用途)

    util__.cloneObject = function(obj, isFlat){
    		var newObj, k;
    		if (obj == null || typeof obj != "object") return obj;
    		if (!isFlat) {
    			newObj = (obj instanceof Array) ? [] : {};
    			for (k in obj) {
    				if (typeof obj[k] == "object") newObj[k] = util__.cloneObject(obj[k], false);
    				else newObj[k] = obj[k];
    			}
    			return newObj;
    		} else return __cloneObjN(obj);
    	};
    
    
    var __cloneObjN = function(target) {
    		if (util__.isFunction(Object.create)) __cloneObjN = function(o) {	return Object.create(o); };
    		else {
    			__cloneObjN = function(o) {
    				function F() {};
    				F.prototype = o;
    				return new F;
    			};
    		}
    		return __cloneObjN(target);
    	};
    

      

  • 相关阅读:
    树套树+【UVALive】6709 Mosaic 二维线段树
    汇编实验1. 计算1+2+3+…+10,将结果显示在屏幕上。4
    Tinkoff Internship Warmup Round 2018 and Codeforces Round #475 (Div. 2) D. Destruction of a Tree
    HDU 4417 Super Mario主席树
    spoj+B
    2018-2019赛季多校联合新生训练赛第五场(2018/12/14)补题题解
    迷宫问题 POJ
    浅谈二分搜索与二分查找
    Moving Tables POJ
    Humidex POJ
  • 原文地址:https://www.cnblogs.com/oxspirt/p/5403497.html
Copyright © 2011-2022 走看看