Last active
November 16, 2015 16:05
-
-
Save xwartz/d5eb31f25d097191238b to your computer and use it in GitHub Desktop.
underscorejs 深拷贝实现
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
// 普通字面量对象的深拷贝 | |
_.cloneDeep = function (obj) { | |
if (typeof(obj) != 'object' || obj == null) return obj; | |
if(obj instanceof Date) { | |
return new Date(obj.getTime()); | |
} | |
var newObj = {}; | |
// 数组 | |
if(Object.prototype.toString.call(obj) === '[object Array]') { | |
newObj = []; | |
} | |
for (var i in obj) { | |
newObj[i] = _.cloneDeep(obj[i]); | |
} | |
return newObj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment