detect types
We can use the below methods:
typeofinstanceofobject.prototype.toString- constructor
What the big difference among them?
Why you can't use 'instanceof' to detect in different window or iframe?
why you can not use 'instanceof' to detect in different window or iframe
instanceof checks to see if a given constructor function is contained in the prototype chain. Different windows/frames have different instances of constructor functions so a constructor function from one window/frame will not match the constructor function from another and thus instanceof will not match them.
As for which method to use, it really depends upon the specific circumstance and what types of things you are trying to discern from one another.
typeof
For discerning two types of objects, typeof is probably the least useful because everything will be reported as an object.
instanceof
instanceof is often useful as long as objects from separate windows/frames won't be involved.
toString
Object.prototype.toString() is useful for discerning the difference between some types of objects such as an Array and a regular Javascript object, but usually doesn't help you with custom objects. For example, you can test if an object is an Array like this:
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array];
}
Obviously, newer browsers have Array.isArray() which offers this functionality, but I included the above for an example of using Object.prototype.tostring().
constructor
The constructor property is really just a less flexible version of instanceof. It only checks the leaf constructor (not any parent constructors) and it has the same multi-window/frame issue that instanceof has. On top of that, not all code properly sets the constructor property. I've very occasionally used the .constructor property when I wanted to make a copy of a particular object that was one of a set of objects known to support a particular type of constructor, but I've not used it for anything else and wouldn't even think about using it for object type checking.
duck typing
I find that "duck typing" is one of the more powerful tools. In duck typing (if it walks and talks like a duck, it must be a duck), you just test to see if your object has the properties and methods that you want to use. If so, it must be a compatible object so you can use them. This has the advantage that any object that supports the right properties and methods will work with your code and it doesn't require a specific implementation.
For example:
// if object supports printing, then print it
if (obj.print) {
obj.print();
}
Note how much more generic this is than checking to see if this object is one of several types known to support printing. In this case the presence or lack of the print method tells the whole story to the code. You can add new object types that do or don't support printing without modifying this code in the least.
Polymorphism
Any time your checking the type of objects, it's worth asking yourself if you should rethink how you're doing things. You really don't want to be writing code that checks to see what type of object something is and then branches behavior based on that if it can be avoided. Instead, you'd rather call a common method on each object and let the object decide what type of behavior is important for implementing that method.
A classic example of this is where you just implement a .draw() method on each object and some top level code can just call .draw() on any of a set of objects without knowing anything about what the type of object is. This polymorphism makes the type of of object irrelevant to the calling code. It just tells each object to perform a task and leaves it up to the given object's implementation to do what is appropriate for that task.
Another handy method in ECMA 6 is to detect the type via the constructor property. This script I've used in Node JS many a time :). It will even find the name of the function if getFuncNames parameter is true
// custom type
function MyType(){
}
var myType = new MyType();
// primitives
var array = [], obj = {}, str = "", date = new Date(),
num = 1, flt = 1.0, reg = new RegExp(/woohoo/g),
bool = true, udf = undefined, nul = null;
// names of various types (primitive and not)
var names = cName(array) + ", " + cName(obj) + ", " + cName(str) + ", " +
cName(num) + ", " + cName(flt) + ", " + cName(reg) + ", " +
cName(bool) + ", " + cName(date) + ", " + cName(myType) + ", " +
cName(MyType) + ", " + cName(udf) + ", " + cName(nul);
console.log( names );
// output: Array, Object, String, Number, Number, RegExp, Boolean, Date, MyType, MyType, undefined, null
// implementation
function cName(obj, getFuncNames){
// default to non-null value.
var ret = '';
if(typeof obj === 'undefined') { ret = 'undefined'; }
else if(obj === null) { ret = String(obj); }
else if(typeof obj.constructor !== 'undefined' && obj.constructor !== null){
ret = obj.constructor.name
if(ret == 'Function' && getFuncNames !== false) { ret = obj.name; }
}
return ret;
}