I always want to keep in mind that object.Create is one of the options, not the only way to achieve non-classical inheritance in javascript.
For myself, I always think that Object.create works best when I want to inherit elements from the prototype chain of the parent objects (i.e. the methods that I would like to apply to the inheriting object).
-
For simple inheritance, the Native Property of Object.create is largely unnecessary. When I want to inherit my own properties, I prefer to use the popular Mixin and Extend templates (which simply copy the properties of one object to another without worrying about the prototype or the βnewβ).
In Stoyan Stefanov's book "Javascript Templates", he gives an example of an extended function that does what you are looking for, recursively, and includes support for properties that are arrays, as well as standard key / value objects:
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; }
If you use jQuery, jQuery.extend () has an optional "deep" argument that allows you to extend the object in almost the same way.
source share