Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a JavaScript object is directly an `{}` instance, not a subclass?

Tags:

javascript

I have spent 10 or 20 minutes here and there probably a dozen times in the past year and never found a bulletproof answer to this question.

How do you check if a JavaScript object is an instance of Object, not a subclass?

One use case for this is to check if arguments[0] is an "options" hash vs. a "model" (MVC), both of which extend the native Object, but which should be treated differently.

I have tried these:

// some helper to get constructor name
function klassName(fn) {
  if (fn.__name__) {
    return fn.__name__;
  }
  if (fn.name) {
    return fn.name;
  }
  return fn.toString().match(/\W*function\s+([\w\$]+)\(/));
};

var Model = function() {};

m = new Model;
o = {};

Object(o) === o; // true
Object(m) === m; // true, thought it might be false

klassName(o.constructor); // Object
klassName(m.constructor); // Model

That klassName(m.constructor) doesn't work in some cases (can't remember exactly, but maybe a regex.constructor, something like that). Maybe it does, don't know for sure.

Is there a bulletproof way to tell if something is an {} object?

like image 852
Lance Avatar asked Apr 25 '12 23:04

Lance


People also ask

How do you know if an object is a subclass?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

How do I know if it's not an instance?

To check if an object is not an instance of a class, use the logical NOT (!) operator to negate the use of the instanceof operator - !( obj instanceof Class) .

Which statement can be used to check if an object obj is an instance of class A?

The instanceof operator. It returns true if obj belongs to the Class or a class inheriting from it.

Which function check if a class is a subclass of another class?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False.


2 Answers

Might something as simple as

function isObj( test ) {
    return test.constructor === Object;
}

Be what you are looking for?

Test in jsFiddle

like image 190
gnarf Avatar answered Oct 23 '22 02:10

gnarf


You mean this? http://jsfiddle.net/elclanrs/ukEEw/

var o = {};
var re = /\d/;
var f = function(){};
var d = new Date();

var isObj = function(e){
    return e.toString() === '[object Object]';
};

console.log( isObj(o) ); // True
console.log( isObj(re) ); // False
console.log( isObj(f) ); // False
console.log( isObj(d) ); // False

like image 27
elclanrs Avatar answered Oct 23 '22 03:10

elclanrs