1

I know about (a instanceof Array) but how would I test for an object?

var c = {};

if ( c instanceof XXXX) {
   // should get thru
}

var s = "abscdef";

if ( s instanceof XXXX) {
   // should not get thru
}

var a = [];

if ( a instanceof XXXX) {
   // should not get thru
}
6
  • what do you mean exactly? {} is an object, not a collection. Commented Jun 10, 2014 at 10:25
  • Your terminology is confused - c is a Object, not a "collection". Commented Jun 10, 2014 at 10:26
  • Ok, sorry then. How to detect an object of any type then? (I edit the question) Commented Jun 10, 2014 at 10:26
  • Same way as array. if (c instanceof Object) ... Commented Jun 10, 2014 at 10:29
  • 1
    @Pilot It's about javascript, so I'd say no. Commented Jun 10, 2014 at 10:30

2 Answers 2

1
function isObject(c) {
  return c instanceof Object 
    && !(c instanceof Array) 
    && !(c instanceof Function)
}

The Array and Function checks are necessary because JavaScript Arrays are also Objects (assuming that you don't want the function to return true for an Array or Function arguments)

Example output:

isObject([])
> false

isObject({})
> true

isObject(1)
> false

isObject('something')
> false

isObject(isObject)
> false
Sign up to request clarification or add additional context in comments.

2 Comments

You can also add && !(c instanceof Function) because c = function(){} is an instance of Object AND Function
Perfect, thanks @joews!: a fiddle to see it in action jsfiddle.net/stephanedeluca/43Jza
0

I think what you mean is something like this? I'm sorry if I don't really understand the question.

function MyOwnType(name){
    this.name = name
}
var myInstance = new MyOwnType("StackOverflow");
console.log(myInstance instanceof(MyOwnType)) //this evaluates to true
console.log(myInstance instanceof(Array)) //this evaluates to false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.