Created
October 21, 2012 15:59
-
-
Save qmmr/3927349 to your computer and use it in GitHub Desktop.
JavaScript: isObject() && getConstructorName()
This file contains hidden or 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 isObject(obj) { | |
return (typeof obj === "object" && obj !== null) || typeof obj === "function"; | |
} | |
function getConstructorName(obj) { | |
return (obj.constructor && obj.constructor.name) ? obj.constructor.name : ""; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if you use this in a copy deep function it will fail. This is an example, so that's why function is not an object.
`
var original = {
a: 1,
b: 2,
c: {
ca: 1,
cb: 2,
d:{
cda: 1,
cdb: 2
}
},
e: function(){
console.log(this.a)
return this.a
}
}
function isObject(obj) {
return (typeof obj === "object" && obj !== null) || typeof obj === "function";
}
function copyDeep(obj){
if(!isObject(obj)) return obj
let newObj = {}
for(let key in obj){
newObj[key] = isObject(obj[key]) ? copyDeep(obj[key]) : obj[key]
}
return newObj
}
var copy = copyDeep(original)
console.log(original.e()) // 1
console.log(copy.e()) // copy.e is not a function
`