热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

JavaScriptPatterns6.5InheritancebyCopyingProperties

ThispostintroduceshowtoimplementtheshallowanddeepcopyinJ

Shallow copy pattern

function extend(parent, child) {

    var i;

    child = child || {};

    for (i in parent) {

        if (parent.hasOwnProperty(i)) {

            child[i] = parent[i];

        }

    }

    return child;

}

 

Deep copy pattern

function extendDeep(parent, child) {

    var i,

    toStr = Object.prototype.toString,

        astr = "[object Array]";

    child = child || {};

    for (i in parent) {

        if (parent.hasOwnProperty(i)) {

            if (typeof parent[i] === "object") {

                child[i] = (toStr.call(parent[i]) === astr) ? [] : {};

                extendDeep(parent[i], child[i]);

            } else {

                child[i] = parent[i];

            }

        }

    }

    return child;

}



var dad = {

    counts: [1, 2, 3],

    reads: {

        paper: true

    }

};

var kid = extendDeep(dad);

kid.counts.push(4);

kid.counts.toString(); // "1,2,3,4"

dad.counts.toString(); // "1,2,3"

(dad.reads === kid.reads).toString(); // false

kid.reads.paper = false;

kid.reads.web = true;

dad.reads.paper; // true

Firebug (Firefox extensions are written in Javascript) has a method called extend()that makes shallow copies  and  jQuery’s  extend() creates  a  deep  copy.  YUI3  offers  a  method  called Y.clone(), which creates a deep copy and also copies over functions by binding them to the child object.

Advantage

There are no prototypes involved in this pattern at all; it’s only about objects and their own properties.

Javascript Patterns 6.5 Inheritance by Copying Properties,,

Javascript Patterns 6.5 Inheritance by Copying Properties


推荐阅读
author-avatar
海峰2502853427
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有