JavaScript Patterns 6.5 Inheritance by Copying Properties
2014-07-19 12:53 小郝(Kaibo Hao) 阅读(289) 评论(0) 编辑 收藏 举报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.
References:
JavaScript Patterns - by Stoyan Stefanov (O`Reilly)
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。