首页 > 代码库 > JavaScript Patterns 6.5 Inheritance by Copying Properties
JavaScript Patterns 6.5 Inheritance by Copying Properties
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(); // falsekid.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.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。