码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript Patterns 6.5 Inheritance by Copying Properties

时间:2014-07-19 14:14:46      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   strong   os   

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,布布扣,bubuko.com

JavaScript Patterns 6.5 Inheritance by Copying Properties

标签:style   blog   java   color   strong   os   

原文地址:http://www.cnblogs.com/haokaibo/p/Inheritance-by-Copying-Properties.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!