I have scanned through related questions here but couldn't find a satisfactory answer on how to determine the type of a JavaScript object.
In fact, the Object.prototype.toString.call(obj)
technique used below is something I got from one of the threads here. However, it seems not to do the job.
Scenario 1:
var Person = function(name)
{
this.name = name;
};
var joe = new Person("Joe Bloggs");
console.log(typeof joe); // prints object
console.log(Object.prototype.toString.call(joe)); // still prints [object Object]
Question: How do I get it to print Person
?
Scenario 2:
var Person = function(...) { };
var Cat = function() { };
var joe = new Person(...);
var polly = new Cat(...);
Question: How do I distinguish between the two objects based on their types? console.log(typeof obj)
or console.log(Object.prototype.toString.call(obj))
on either of them will yield the same result.
instanceof
I am aware of instanceof
but that's not a swiss army knife. It is tedious in that it can only be applied for testing whether or not an object is of a certain type. How do I get to know the type of an object?