• 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);
    	};
    

      

  • 相关阅读:
    Jquery之高亮显示
    JS之旋转轮播图
    JS之手风琴效果
    JS之评价页面点亮星星进行评价
    JS之京东淘宝图片放大镜效果
    JS之表单验证
    JS之拖拽案例
    禁止文本选中
    大数据告诉你:学历真的能改变命运
    hadoop的自定义分组实现 (Partition机制)
  • 原文地址:https://www.cnblogs.com/oxspirt/p/5403497.html
Copyright © 2020-2023  润新知