Skip to content

Instantly share code, notes, and snippets.

@qmmr
Created October 21, 2012 15:59
Show Gist options
  • Save qmmr/3927349 to your computer and use it in GitHub Desktop.
Save qmmr/3927349 to your computer and use it in GitHub Desktop.
JavaScript: isObject() && getConstructorName()
function isObject(obj) {
return (typeof obj === "object" && obj !== null) || typeof obj === "function";
}
function getConstructorName(obj) {
return (obj.constructor && obj.constructor.name) ? obj.constructor.name : "";
}
@hasip-timurtas
Copy link

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

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment