Last active
February 12, 2017 16:01
-
-
Save vidul-nikolaev-petrov/3181ada0620754e1f6817a716fcb7a8b to your computer and use it in GitHub Desktop.
ES5 extend object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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