标签:javascript 面向对象编程 js 编程语言
/** * 通过拷贝继承对象的属性和行为 * @param {Object} p 父对象 */ function extendCopy(p) { var c = {}; for (var i in p) { c[i] = p[i]; } c.uber = p; return c; }
var shape = { name: 'shape', toString: function() {return this.name;} } var twoDee = extendCopy(shape); twoDee.name = '2D shape'; twoDee.toString = function(){return this.uber.toString() + ', ' + this.name;}; var triangle = extendCopy(twoDee); triangle.name = 'Triangle'; triangle.getArea = function(){return this.side * this.height / 2;} //使用继承而来的toString方法 alert(triangle.toString());
/** * 深度拷贝 * @param {Object} p 父对象 * @param {Object} c 子对象 */ function deepCopy(p, c) { var c = c || {}; for (var i in p) { if (typeof p[i] === 'object') { c[i] = (p[i].constructor === Array) ? [] : {}; deepCopy(p[i], c[i]); } else { c[i] = p[i]; } } return c; }
JavaScript面向对象编程(10)快速构建继承关系之对象拷贝
标签:javascript 面向对象编程 js 编程语言
原文地址:http://blog.csdn.net/zhengwei223/article/details/42112127