Skip to content

Instantly share code, notes, and snippets.

@vidul-nikolaev-petrov
Last active February 12, 2017 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vidul-nikolaev-petrov/3181ada0620754e1f6817a716fcb7a8b to your computer and use it in GitHub Desktop.
Save vidul-nikolaev-petrov/3181ada0620754e1f6817a716fcb7a8b to your computer and use it in GitHub Desktop.
ES5 extend object
function extendObject(parent, child) {
var copyFunction = function (f) {
var t = function () {
return f.apply(this, arguments);
};
Object.defineProperty(t, 'name', {
value: f.name,
});
return t;
},
isObject = function (val) {
return (typeof val === 'object' && val);
},
isFunction = function (val) {
return (typeof val === 'function');
},
getType = function (val) {
if (isObject(val)) return extendObject(val);
if (isFunction(val)) return copyFunction(val);
return val;
};
child = child || {};
Object.keys(parent).forEach(function (p) {
var list = [],
val = parent[p];
if (isObject(val)) {
if (val instanceof Array) {
for (var x = val.length; x--;) {
list[x] = getType(val[x]);
}
child[p] = list;
}
else {
child[p] = extendObject(val);
}
}
else if (isFunction(val)) {
child[p] = copyFunction(val);
Object.keys(val).forEach(function (fp) {
child[p][fp] = getType(val[fp]);
});
}
else {
child[p] = val;
}
});
return child;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment