Created
March 17, 2012 21:19
-
-
Save iwyg/2065392 to your computer and use it in GitHub Desktop.
deep extend or copy an 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 () { | |
var objStr = '[object Object]'; | |
//var arrStr = '[object Array]'; | |
//var isArray = function (a) { | |
// return Object.prototype.toString.call(a) === arrStr; | |
//}; | |
var isObject = function (o) { | |
return Object.prototype.toString.call(o) === objStr; | |
}; | |
var objExtend = function (a, b, deep) { | |
var key, val; | |
deep = typeof deep === 'boolean'; | |
for (key in b) { | |
if (b.hasOwnProperty(key)) { | |
a[key] = (deep && isObject(b[key])) ? objExtend(a[key] && isObject(a[key]) ? a[key] : {}, b[key]) : b[key]; | |
} | |
} | |
return a; | |
}; | |
/** | |
* @param o1 {Object} the Object to be extended | |
* @param o2 {Object} the Object that holds the properties/methods | |
* which o1 should be extended with; | |
* @param options {Object} takes 2 properties: copy and deep | |
* | |
* select copy and a extended copy of the o1 Object will be returned | |
* instread of the extended o1 object; | |
* | |
* select deep for a deep extension / copy | |
*/ | |
var extend = function (o1, o2, options) { | |
options = options || {}; | |
var copy = !!options.copy, | |
o = !copy ? o1 : objExtend({}, o1, true); | |
return objExtend(o, o2, !!options.deep); | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment