How to "type check" function parameters? - javascript

What's the best way to check the type for objects created by Object.create or literal, for example the following code. I want to make sure the arguments to the function is safe to use. Maybe I shouldn't check the type of arguments, but check whether the properties the function uses are not undefined. But it seems very tedious to do so. What's the best approach, thanks.
var base = {
name : "abc"
};
var child = Object.create(base);
do_something = function(o) {
if (typeof(o) === "base") { // will not work
...
}
}

typeof can only return the base type like, object, strirng, number, undefined.
typeof o === "object"
instanceof can be used if you are inheriting from the base class. Eg here MDN
function Base() {
this.name = "abc";
}
var child = new Base();
var a = child instanceof Base; //true
instance of expects the format <object> insanceof <function>
You can use isPrototypeOf() when inheriting using Object.create()
var base = {name; "abc"};
var child = Object.create(base);
base.isPrototypeOf(child);
More info can be read here: Mozilla Developer Network: isPrototypeOf
To check if there exists an object o with the attribute name non empty, you can do
if(typeof o === "object" && typeof o.name !== "undefined")
A shorthand can be used, if name will not hold falsy values like 0
if(o && o.name)

In your code base is a variable not a type, In JavaScript function are treated as classes if you want base type then create a function and initialize it and then use instanceof that will give you base.
Try this way using instanceof:
var base = function(){
name : "abc"
};
var o = new base();
alert(o instanceof base); // true
Here is JsFiddle

Related

How to distinguish HTMLElement from its constructor.prototype?

I'm working on my LIPS project (Scheme-based Lisp in JavaScript) and I want to add a way to add string representation to any object. The code look like this:
NOTE: you can ignore scheme code. At the end there is simplified use case, this is only for context and why I need this.
(add-repr! HTMLElement (lambda (x)
(let ((tag (--> x.tagName (toLowerCase))))
(string-append "<" tag ">" x.innerHTML "</" tag ">"))))
it works fine when I evaluate:
(document.createElement "span")
;; or
(document.querySelector ".klas")
but it have problem while evaluating the code:
(let ((div (document.createElement "div")))
(. div 'constructor 'prototype))
and my interpreter thinks that this is instance of HTMLElement, the JavaScript code look like this:
var repr = new Map();
// values in map are lisp lambdas that are JavaScript functions
// keys are constructor functions
...
var fn;
if (repr.has(constructor)) {
fn = repr.get(constructor);
} else {
repr.forEach(function(value, key) {
if (obj instanceof key) {
fn = value;
}
});
}
if (fn) {
if (typeof fn === 'function') {
return fn(obj, quote);
} else {
throw new Error('toString: Invalid repr value');
}
}
I check if obj is instanceof given type (HTMLElement from add-repr!) and it return true for prototype.
And throw exception that x.tagName is not defined because it's not instance but prototype.
To simplify the code (I've added scheme code for context) this is the code:
document.createElement('div').constructor.prototype instanceof HTMLElement;
it return true because prototype was Object.create(HTMLElement). Is there a way to detect if the value is in fact a prototype of any value without have that original value.
var x = document.createElement('div').constructor.prototype;
// context is lost I can't access original value
// check if x is instanceof HTMLElement, but also it's constructed value and not prototype of any value.
and if you think that you can check if there is constructor value, this circular object:
document.createElement('div').constructor.prototype.constructor.prototype.constructor
to sum this question up I want to detect if value is any of but not both:
document.createElement('div')
document.createElement('div').constructor.prototype
My idea that just came to my mind while I was writing this was this:
var x = document.createElement('div').constructor.prototype;
if (x instanceof HTMLElement && x !== x.constructor.prototype) {
// real instance
}
is this correct approach? I was also looking at Object.getPrototypeOf but it just return HTMLElement object (the one I'm testing). I need this to work for any nested prototype chain, because it's programming construct and user may use anything.
For detecting whether something is a prototype object, irrespective of HTMLElement, I would suggest doing
hasOwnProperty(x, "constructor") &&
typeof x.constructor == "function" &&
x.constructor.prototype == x
The context of the expression the user is trying to evaluate doesn't matter, they might as well try printing (. HTMLElement 'prototype) directly.
Separately, I would suggest not tying the "representation" function for instances to its constructor through a Map. Your add-repr! should just create a .repr() method on the prototype of the class, using Symbol("lips-repr()") as the property key.

Find out what kind of object a thing is in Javascript/Coffeescript when foo.prototype is undefined? [duplicate]

Is there a JavaScript equivalent of Java's class.getName()?
Is there a JavaScript equivalent of Java's class.getName()?
No.
ES2015 Update: the name of class Foo {} is Foo.name. The name of thing's class, regardless of thing's type, is thing.constructor.name. Builtin constructors in an ES2015 environment have the correct name property; for instance (2).constructor.name is "Number".
But here are various hacks that all fall down in one way or another:
Here is a hack that will do what you need - be aware that it modifies the Object's prototype, something people frown upon (usually for good reason)
Object.prototype.getName = function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
};
Now, all of your objects will have the function, getName(), that will return the name of the constructor as a string. I have tested this in FF3 and IE7, I can't speak for other implementations.
If you don't want to do that, here is a discussion on the various ways of determining types in JavaScript...
I recently updated this to be a bit more exhaustive, though it is hardly that. Corrections welcome...
Using the constructor property...
Every object has a value for its constructor property, but depending on how that object was constructed as well as what you want to do with that value, it may or may not be useful.
Generally speaking, you can use the constructor property to test the type of the object like so:
var myArray = [1,2,3];
(myArray.constructor == Array); // true
So, that works well enough for most needs. That said...
Caveats
Will not work AT ALL in many cases
This pattern, though broken, is quite common:
function Thingy() {
}
Thingy.prototype = {
method1: function() {
},
method2: function() {
}
};
Objects constructed via new Thingy will have a constructor property that points to Object, not Thingy. So we fall right at the outset; you simply cannot trust constructor in a codebase that you don't control.
Multiple Inheritance
An example where it isn't as obvious is using multiple inheritance:
function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a
Things now don't work as you might expect them to:
var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true
So, you might get unexpected results if the object your testing has a different object set as its prototype. There are ways around this outside the scope of this discussion.
There are other uses for the constructor property, some of them interesting, others not so much; for now we will not delve into those uses since it isn't relevant to this discussion.
Will not work cross-frame and cross-window
Using .constructor for type checking will break when you want to check the type of objects coming from different window objects, say that of an iframe or a popup window. This is because there's a different version of each core type constructor in each `window', i.e.
iframe.contentWindow.Array === Array // false
Using the instanceof operator...
The instanceof operator is a clean way of testing object type as well, but has its own potential issues, just like the constructor property.
var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true
But instanceof fails to work for literal values (because literals are not Objects)
3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false
The literals need to be wrapped in an Object in order for instanceof to work, for example
new Number(3) instanceof Number // true
The .constructor check works fine for literals because the . method invocation implicitly wraps the literals in their respective object type
3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true
Why two dots for the 3? Because Javascript interprets the first dot as a decimal point ;)
Will not work cross-frame and cross-window
instanceof also will not work across different windows, for the same reason as the constructor property check.
Using the name property of the constructor property...
Does not work AT ALL in many cases
Again, see above; it's quite common for constructor to be utterly and completely wrong and useless.
Does NOT work in <IE9
Using myObjectInstance.constructor.name will give you a string containing the name of the constructor function used, but is subject to the caveats about the constructor property that were mentioned earlier.
For IE9 and above, you can monkey-patch in support:
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s+([^\s(]+)\s*\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1] : "";
},
set: function(value) {}
});
}
Updated version from the article in question. This was added 3 months after the article was published, this is the recommended version to use by the article's author Matthew Scharley. This change was inspired by comments pointing out potential pitfalls in the previous code.
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s([^(]{1,})\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1].trim() : "";
},
set: function(value) {}
});
}
Using Object.prototype.toString
It turns out, as this post details, you can use Object.prototype.toString - the low level and generic implementation of toString - to get the type for all built-in types
Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]
One could write a short helper function such as
function type(obj){
return Object.prototype.toString.call(obj).slice(8, -1);
}
to remove the cruft and get at just the type name
type('abc') // String
However, it will return Object for all user-defined types.
Caveats for all...
All of these are subject to one potential problem, and that is the question of how the object in question was constructed. Here are various ways of building objects and the values that the different methods of type checking will return:
// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == "Foo"); // true
// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // false
(obj.constructor.name == "Foo"); // false
// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object); // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == ""); // true
// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object); // true
(obj instanceof Foo); // true
(obj.constructor == Foo); // true
(obj.constructor.name == ""); // true
// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object); // true
(obj.constructor == Object); // true
(obj.constructor.name == "Object"); // true
While not all permutations are present in this set of examples, hopefully there are enough to provide you with an idea about how messy things might get depending on your needs. Don't assume anything, if you don't understand exactly what you are after, you may end up with code breaking where you don't expect it to because of a lack of grokking the subtleties.
NOTE:
Discussion of the typeof operator may appear to be a glaring omission, but it really isn't useful in helping to identify whether an object is a given type, since it is very simplistic. Understanding where typeof is useful is important, but I don't currently feel that it is terribly relevant to this discussion. My mind is open to change though. :)
Jason Bunting's answer gave me enough of a clue to find what I needed:
<<Object instance>>.constructor.name
So, for example, in the following piece of code:
function MyObject() {}
var myInstance = new MyObject();
myInstance.constructor.name would return "MyObject".
A little trick I use:
function Square(){
this.className = "Square";
this.corners = 4;
}
var MySquare = new Square();
console.log(MySquare.className); // "Square"
Update
To be precise, I think OP asked for a function that retrieves the constructor name for a particular object. In terms of Javascript, object does not have a type but is a type of and in itself. However, different objects can have different constructors.
Object.prototype.getConstructorName = function () {
var str = (this.prototype ? this.prototype.constructor : this.constructor).toString();
var cname = str.match(/function\s(\w*)/)[1];
var aliases = ["", "anonymous", "Anonymous"];
return aliases.indexOf(cname) > -1 ? "Function" : cname;
}
new Array().getConstructorName(); // returns "Array"
(function () {})().getConstructorName(); // returns "Function"
 
Note: the below example is deprecated.
A blog post linked by Christian Sciberras contains a good example on how to do it. Namely, by extending the Object prototype:
if (!Object.prototype.getClassName) {
Object.prototype.getClassName = function () {
return Object.prototype.toString.call(this).match(/^\[object\s(.*)\]$/)[1];
}
}
var test = [1,2,3,4,5];
alert(test.getClassName()); // returns Array
Using Object.prototype.toString
It turns out, as this post details, you can use Object.prototype.toString - the low level and generic implementation of toString - to get the type for all built-in types
Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]
One could write a short helper function such as
function type(obj){
return Object.prototype.toString.call(obj]).match(/\s\w+/)[0].trim()
}
return [object String] as String
return [object Number] as Number
return [object Object] as Object
return [object Undefined] as Undefined
return [object Function] as Function
You should use somevar.constructor.name like a:
const getVariableType = a => a.constructor.name.toLowerCase();
const d = new Date();
const res1 = getVariableType(d); // 'date'
const num = 5;
const res2 = getVariableType(num); // 'number'
const fn = () => {};
const res3 = getVariableType(fn); // 'function'
console.log(res1); // 'date'
console.log(res2); // 'number'
console.log(res3); // 'function'
Here is a solution that I have come up with that solves the shortcomings of instanceof. It can check an object's types from cross-windows and cross-frames and doesn't have problems with primitive types.
function getType(o) {
return Object.prototype.toString.call(o).match(/^\[object\s(.*)\]$/)[1];
}
function isInstance(obj, type) {
var ret = false,
isTypeAString = getType(type) == "String",
functionConstructor, i, l, typeArray, context;
if (!isTypeAString && getType(type) != "Function") {
throw new TypeError("type argument must be a string or function");
}
if (obj !== undefined && obj !== null && obj.constructor) {
//get the Function constructor
functionConstructor = obj.constructor;
while (functionConstructor != functionConstructor.constructor) {
functionConstructor = functionConstructor.constructor;
}
//get the object's window
context = functionConstructor == Function ? self : functionConstructor("return window")();
//get the constructor for the type
if (isTypeAString) {
//type is a string so we'll build the context (window.Array or window.some.Type)
for (typeArray = type.split("."), i = 0, l = typeArray.length; i < l && context; i++) {
context = context[typeArray[i]];
}
} else {
//type is a function so execute the function passing in the object's window
//the return should be a constructor
context = type(context);
}
//check if the object is an instance of the constructor
if (context) {
ret = obj instanceof context;
if (!ret && (type == "Number" || type == "String" || type == "Boolean")) {
ret = obj.constructor == context
}
}
}
return ret;
}
isInstance requires two parameters: an object and a type. The real trick to how it works is that it checks if the object is from the same window and if not gets the object's window.
Examples:
isInstance([], "Array"); //true
isInstance("some string", "String"); //true
isInstance(new Object(), "Object"); //true
function Animal() {}
function Dog() {}
Dog.prototype = new Animal();
isInstance(new Dog(), "Dog"); //true
isInstance(new Dog(), "Animal"); //true
isInstance(new Dog(), "Object"); //true
isInstance(new Animal(), "Dog"); //false
The type argument can also be a callback function which returns a constructor. The callback function will receive one parameter which is the window of the provided object.
Examples:
//"Arguments" type check
var args = (function() {
return arguments;
}());
isInstance(args, function(w) {
return w.Function("return arguments.constructor")();
}); //true
//"NodeList" type check
var nl = document.getElementsByTagName("*");
isInstance(nl, function(w) {
return w.document.getElementsByTagName("bs").constructor;
}); //true
One thing to keep in mind is that IE < 9 does not provide the constructor on all objects so the above test for NodeList would return false and also a isInstance(alert, "Function") would return false.
I was actually looking for a similar thing and came across this question. Here is how I get types: jsfiddle
var TypeOf = function ( thing ) {
var typeOfThing = typeof thing;
if ( 'object' === typeOfThing ) {
typeOfThing = Object.prototype.toString.call( thing );
if ( '[object Object]' === typeOfThing ) {
if ( thing.constructor.name ) {
return thing.constructor.name;
}
else if ( '[' === thing.constructor.toString().charAt(0) ) {
typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );
}
else {
typeOfThing = thing.constructor.toString().match( /function\s*(\w+)/ );
if ( typeOfThing ) {
return typeOfThing[1];
}
else {
return 'Function';
}
}
}
else {
typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );
}
}
return typeOfThing.charAt(0).toUpperCase() + typeOfThing.slice(1);
}
Use constructor.name when you can, and regex function when I can't.
Function.prototype.getName = function(){
if (typeof this.name != 'undefined')
return this.name;
else
return /function (.+)\(/.exec(this.toString())[1];
};
The kind() function from Agave.JS will return:
the closest prototype in the inheritance tree
for always-primitive types like 'null' and 'undefined', the primitive name.
It works on all JS objects and primitives, regardless of how they were created, and doesn't have any surprises.
var kind = function(item) {
var getPrototype = function(item) {
return Object.prototype.toString.call(item).slice(8, -1);
};
var kind, Undefined;
if (item === null ) {
kind = 'null';
} else {
if ( item === Undefined ) {
kind = 'undefined';
} else {
var prototype = getPrototype(item);
if ( ( prototype === 'Number' ) && isNaN(item) ) {
kind = 'NaN';
} else {
kind = prototype;
}
}
}
return kind;
};
Examples:
Numbers
kind(37) === 'Number'
kind(3.14) === 'Number'
kind(Math.LN2) === 'Number'
kind(Infinity) === 'Number'
kind(Number(1)) === 'Number'
kind(new Number(1)) === 'Number'
NaN
kind(NaN) === 'NaN'
Strings
kind('') === 'String'
kind('bla') === 'String'
kind(String("abc")) === 'String'
kind(new String("abc")) === 'String'
Booleans
kind(true) === 'Boolean'
kind(false) === 'Boolean'
kind(new Boolean(true)) === 'Boolean'
Arrays
kind([1, 2, 4]) === 'Array'
kind(new Array(1, 2, 3)) === 'Array'
Objects
kind({a:1}) === 'Object'
kind(new Object()) === 'Object'
Dates
kind(new Date()) === 'Date'
Functions
kind(function(){}) === 'Function'
kind(new Function("console.log(arguments)")) === 'Function'
kind(Math.sin) === 'Function'
undefined
kind(undefined) === 'undefined'
null
kind(null) === 'null'
Here is an implementation based on the accepted answer:
/**
* Describes the type of a variable.
*/
class VariableType
{
type;
name;
/**
* Creates a new VariableType.
*
* #param {"undefined" | "null" | "boolean" | "number" | "bigint" | "array" | "string" | "symbol" |
* "function" | "class" | "object"} type the name of the type
* #param {null | string} [name = null] the name of the type (the function or class name)
* #throws {RangeError} if neither <code>type</code> or <code>name</code> are set. If <code>type</code>
* does not have a name (e.g. "number" or "array") but <code>name</code> is set.
*/
constructor(type, name = null)
{
switch (type)
{
case "undefined":
case "null":
case "boolean" :
case "number" :
case "bigint":
case "array":
case "string":
case "symbol":
if (name !== null)
throw new RangeError(type + " may not have a name");
}
this.type = type;
this.name = name;
}
/**
* #return {string} the string representation of this object
*/
toString()
{
let result;
switch (this.type)
{
case "function":
case "class":
{
result = "a ";
break;
}
case "object":
{
result = "an ";
break;
}
default:
return this.type;
}
result += this.type;
if (this.name !== null)
result += " named " + this.name;
return result;
}
}
const functionNamePattern = /^function\s+([^(]+)?\(/;
const classNamePattern = /^class(\s+[^{]+)?{/;
/**
* Returns the type information of a value.
*
* <ul>
* <li>If the input is undefined, returns <code>(type="undefined", name=null)</code>.</li>
* <li>If the input is null, returns <code>(type="null", name=null)</code>.</li>
* <li>If the input is a primitive boolean, returns <code>(type="boolean", name=null)</code>.</li>
* <li>If the input is a primitive number, returns <code>(type="number", name=null)</code>.</li>
* <li>If the input is a primitive or wrapper bigint, returns
* <code>(type="bigint", name=null)</code>.</li>
* <li>If the input is an array, returns <code>(type="array", name=null)</code>.</li>
* <li>If the input is a primitive string, returns <code>(type="string", name=null)</code>.</li>
* <li>If the input is a primitive symbol, returns <code>(type="symbol", null)</code>.</li>
* <li>If the input is a function, returns <code>(type="function", name=the function name)</code>. If the
* input is an arrow or anonymous function, its name is <code>null</code>.</li>
* <li>If the input is a function, returns <code>(type="function", name=the function name)</code>.</li>
* <li>If the input is a class, returns <code>(type="class", name=the name of the class)</code>.
* <li>If the input is an object, returns
* <code>(type="object", name=the name of the object's class)</code>.
* </li>
* </ul>
*
* Please note that built-in types (such as <code>Object</code>, <code>String</code> or <code>Number</code>)
* may return type <code>function</code> instead of <code>class</code>.
*
* #param {object} value a value
* #return {VariableType} <code>value</code>'s type
* #see http://stackoverflow.com/a/332429/14731
* #see isPrimitive
*/
function getTypeInfo(value)
{
if (value === null)
return new VariableType("null");
const typeOfValue = typeof (value);
const isPrimitive = typeOfValue !== "function" && typeOfValue !== "object";
if (isPrimitive)
return new VariableType(typeOfValue);
const objectToString = Object.prototype.toString.call(value).slice(8, -1);
// eslint-disable-next-line #typescript-eslint/ban-types
const valueToString = value.toString();
if (objectToString === "Function")
{
// A function or a constructor
const indexOfArrow = valueToString.indexOf("=>");
const indexOfBody = valueToString.indexOf("{");
if (indexOfArrow !== -1 && (indexOfBody === -1 || indexOfArrow < indexOfBody))
{
// Arrow function
return new VariableType("function");
}
// Anonymous and named functions
const functionName = functionNamePattern.exec(valueToString);
if (functionName !== null && typeof (functionName[1]) !== "undefined")
{
// Found a named function or class constructor
return new VariableType("function", functionName[1].trim());
}
const className = classNamePattern.exec(valueToString);
if (className !== null && typeof (className[1]) !== "undefined")
{
// When running under ES6+
return new VariableType("class", className[1].trim());
}
// Anonymous function
return new VariableType("function");
}
if (objectToString === "Array")
return new VariableType("array");
const classInfo = getTypeInfo(value.constructor);
return new VariableType("object", classInfo.name);
}
function UserFunction()
{
}
function UserClass()
{
}
let anonymousFunction = function()
{
};
let arrowFunction = i => i + 1;
console.log("getTypeInfo(undefined): " + getTypeInfo(undefined));
console.log("getTypeInfo(null): " + getTypeInfo(null));
console.log("getTypeInfo(true): " + getTypeInfo(true));
console.log("getTypeInfo(5): " + getTypeInfo(5));
console.log("getTypeInfo(\"text\"): " + getTypeInfo("text"));
console.log("getTypeInfo(userFunction): " + getTypeInfo(UserFunction));
console.log("getTypeInfo(anonymousFunction): " + getTypeInfo(anonymousFunction));
console.log("getTypeInfo(arrowFunction): " + getTypeInfo(arrowFunction));
console.log("getTypeInfo(userObject): " + getTypeInfo(new UserClass()));
console.log("getTypeInfo(nativeObject): " + getTypeInfo(navigator.mediaDevices.getUserMedia));
We only use the constructor property when we have no other choice.
You can use the instanceof operator to see if an object is an instance of another, but since there are no classes, you can't get a class name.
You can use the "instanceof" operator to determine if an object is an instance of a certain class or not. If you do not know the name of an object's type, you can use its constructor property. The constructor property of objects, is a reference to the function that is used to initialize them. Example:
function Circle (x,y,radius) {
this._x = x;
this._y = y;
this._radius = raduius;
}
var c1 = new Circle(10,20,5);
Now c1.constructor is a reference to the Circle() function.
You can alsow use the typeof operator, but the typeof operator shows limited information. One solution is to use the toString() method of the Object global object. For example if you have an object, say myObject, you can use the toString() method of the global Object to determine the type of the class of myObject. Use this:
Object.prototype.toString.apply(myObject);
Say you have var obj;
If you just want the name of obj's type, like "Object", "Array", or "String",
you can use this:
Object.prototype.toString.call(obj).split(' ')[1].replace(']', '');
The closest you can get is typeof, but it only returns "object" for any sort of custom type. For those, see Jason Bunting.
Edit, Jason's deleted his post for some reason, so just use Object's constructor property.
For of those of you reading this and want a simple solution that works fairly well and has been tested:
const getTypeName = (thing) => {
const name = typeof thing
if (name !== 'object') return name
if (thing instanceof Error) return 'error'
if (!thing) return 'null'
return ({}).toString.call(thing).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
To get insight on why this works, checkout the polyfill documentation for Array.isArray(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray#polyfill
If anyone was looking for a solution which is working with jQuery, here is the adjusted wiki code (the original breaks jQuery).
Object.defineProperty(Object.prototype, "getClassName", {
value: function() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec((this).constructor.toString());
return (results && results.length > 1) ? results[1] : "";
}
});
Lodash has many isMethods so if you're using Lodash maybe a mixin like this can be useful:
// Mixin for identifying a Javascript Object
_.mixin({
'identify' : function(object) {
var output;
var isMethods = ['isArguments', 'isArray', 'isArguments', 'isBoolean', 'isDate', 'isArguments',
'isElement', 'isError', 'isFunction', 'isNaN', 'isNull', 'isNumber',
'isPlainObject', 'isRegExp', 'isString', 'isTypedArray', 'isUndefined', 'isEmpty', 'isObject']
this.each(isMethods, function (method) {
if (this[method](object)) {
output = method;
return false;
}
}.bind(this));
return output;
}
});
It adds a method to lodash called "identify" which works as follow:
console.log(_.identify('hello friend')); // isString
Plunker:
http://plnkr.co/edit/Zdr0KDtQt76Ul3KTEDSN
Ok, folks I've been slowly building a catch all method for this over some years lol! The trick is to:
Have a mechanism for creating classes.
Have a mechanism for checking all user created classes, primitives and values created/generated by native constructors.
Have a mechanism for extending user created classes into new ones so that the above functionality permeates through your code/application/library/etc..
For an example (or to see how I dealt with the problem) look at the following code on github: https://github.com/elycruz/sjljs/blob/master/src/sjl/sjl.js and search for:
classOf =,
classOfIs =, and or
defineSubClass = (without the backticks (`)).
As you can see I have some mechanisms in place to force classOf to always give me the classes/constructors type name regardless of whether it is a primitive, a user defined class, a value created using a native constructor, Null, NaN, etc.. For every single javascript value I will get it's unique type name from the classOf function. In addition I can pass in actual constructors into sjl.classOfIs to check a value's type in addition to being able to pass in it's type name as well! So for example:
```
// Please forgive long namespaces! I had no idea on the impact until after using them for a while (they suck haha)
var SomeCustomClass = sjl.package.stdlib.Extendable.extend({
constructor: function SomeCustomClass () {},
// ...
}),
HelloIterator = sjl.ns.stdlib.Iterator.extend(
function HelloIterator () {},
{ /* ... methods here ... */ },
{ /* ... static props/methods here ... */ }
),
helloIt = new HelloIterator();
sjl.classOfIs(new SomeCustomClass(), SomeCustomClass) === true; // `true`
sjl.classOfIs(helloIt, HelloIterator) === true; // `true`
var someString = 'helloworld';
sjl.classOfIs(someString, String) === true; // `true`
sjl.classOfIs(99, Number) === true; // true
sjl.classOf(NaN) === 'NaN'; // true
sjl.classOf(new Map()) === 'Map';
sjl.classOf(new Set()) === 'Set';
sjl.classOfIs([1, 2, 4], Array) === true; // `true`
// etc..
// Also optionally the type you want to check against could be the type's name
sjl.classOfIs(['a', 'b', 'c'], 'Array') === true; // `true`!
sjl.classOfIs(helloIt, 'HelloIterator') === true; // `true`!
```
If you are interested in reading more on how I use the setup mentioned above take a look at the repo: https://github.com/elycruz/sjljs
Also books with content on the subject:
- "JavaScript Patterns" by Stoyan Stefanov.
- "Javascript - The Definitive Guide." by David Flanagan.
- and many others.. (search le` web).
Also you can quickly test the features I'm talking about here:
- http://sjljs.elycruz.com/0.5.18/tests/for-browser/ (also the 0.5.18 path in the url has the sources from github on there minus the node_modules and such).
Happy Coding!
Fairly Simple!
My favorite method to get type of anything in JS
function getType(entity){
var x = Object.prototype.toString.call(entity)
return x.split(" ")[1].split(']')[0].toLowerCase()
}
my favorite method to check type of anything in JS
function checkType(entity, type){
return getType(entity) === type
}
Use class.name. This also works with function.name.
class TestA {}
console.log(TestA.name); // "TestA"
function TestB() {}
console.log(TestB.name); // "TestB"

What did Douglas Crockford mean by 'constructed in a different window or frame'?

What does Douglas Crockford mean when he wrote the is_array() test saying that it will fail to identify arrays that were constructed in a different window or frame?
var is_array = function (value) {
return value &&
typeof value === 'object' &&
value.constructor === Array;
Why does the following work across windows and frames?
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
For example, if you have an iframe, which has its own window, any Array constructed in there will fail another window's test. That's because of the last condition, which assumes the current window's Array, which is a different object.
var isArray = document.querySelector("iframe").contentWindow.Array === Array;
// false (wrong, it *is* an array)
jsFiddle.
The latter works through knowing that typeof always says an Array is an "object", as well as looking for properties that exist on Arrays.
However, it can be fooled, by constructing an object that looks like an array.
var isArray = is_array(Object.create({length: 0, splice: function() {}}));
// true (wrong, it *isn't* an array)
jsFiddle.
Another method is to invoke Object's toString() method on it, which will return the internal class.
var isArray = ({}).toString.call(value) == "[object Array]";
// true (correct, it's an array)
jsFiddle.
This works in a multi-window environment and can't be tricked (though there is more overhead examining it this way, but never likely to be a bottleneck).
I think alex's solution is better than Crockford's. This answer is to point the flaw in Crockford's solution.
See this:
I purposefully created a faulty object.
function Stupid(){}
Stupid.prototype.length = 0;
Stupid.prototype.splice = function () {}
var stupid = new Stupid();
is_array(stupid);
// true
Obviously, if you see someone setting length to the prototype, you have every right to smash their head to the wall.
But this is valid:
function Mediocre(){
Object.defineProperty(this, 'length', {
get: function () { return 42; },
enumerable: false
});
}
Mediocre.prototype.splice = function () {}
var m = new Mediocre();
is_array(m);
// true
So, you shouldn't try to outsmart the usual/common methods, because you can't guess what the other developers are going to do.

Better way to get type of a Javascript variable?

Is there a better way to get the type of a variable in JS than typeof? It works fine when you do:
> typeof 1
"number"
> typeof "hello"
"string"
But it's useless when you try:
> typeof [1,2]
"object"
>r = new RegExp(/./)
/./
> typeof r
"function"
I know of instanceof, but this requires you to know the type beforehand.
> [1,2] instanceof Array
true
> r instanceof RegExp
true
Is there a better way?
Angus Croll recently wrote an interesting blog post about this -
http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
He goes through the pros and cons of the various methods then defines a new method 'toType' -
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
You can try using constructor.name.
[].constructor.name
new RegExp().constructor.name
As with everything JavaScript, someone will eventually invariably point that this is somehow evil, so here is a link to an answer that covers this pretty well.
An alternative is to use Object.prototype.toString.call
Object.prototype.toString.call([])
Object.prototype.toString.call(/./)
You may find the following function useful:
function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
Or in ES7 (comment if further improvements)
const { toString } = Object.prototype;
function typeOf(obj) {
const stringified = obj::toString();
const type = stringified.split(' ')[1].slice(0, -1);
return type.toLowerCase();
}
Results:
typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new Error) //error
typeOf(Promise.resolve()) //promise
typeOf(function *() {}) //generatorfunction
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map
typeOf(async function() {}) //asyncfunction
Thanks #johnrees for notifying me of: error, promise, generatorfunction
A reasonably good type capture function is the one used by YUI3:
var TYPES = {
'undefined' : 'undefined',
'number' : 'number',
'boolean' : 'boolean',
'string' : 'string',
'[object Function]': 'function',
'[object RegExp]' : 'regexp',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object Error]' : 'error'
},
TOSTRING = Object.prototype.toString;
function type(o) {
return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};
This captures many of the primitives provided by javascript, but you can always add more by modifying the TYPES object. Note that typeof HTMLElementCollection in Safari will report function, but type(HTMLElementCollection) will return object
Also we can change a little example from ipr101
Object.prototype.toType = function() {
return ({}).toString.call(this).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
and call as
"aaa".toType(); // 'string'
one line function:
function type(obj) {
return Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/,"$1").toLowerCase()
}
this give the same result as jQuery.type()
You can apply Object.prototype.toString to any object:
var toString = Object.prototype.toString;
console.log(toString.call([]));
//-> [object Array]
console.log(toString.call(/reg/g));
//-> [object RegExp]
console.log(toString.call({}));
//-> [object Object]
This works well in all browsers, with the exception of IE - when calling this on a variable obtained from another window it will just spit out [object Object].
function getType(obj) {
if(obj && obj.constructor && obj.constructor.name) {
return obj.constructor.name;
}
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
In my preliminary tests, this is working pretty well. The first case will print the name of any object created with "new", and the 2nd case should catch everything else.
I'm using (8, -1) because I'm assuming that the result is always going to start with [object and end with ] but I'm not certain that's true in every scenario.
My 2¢! Really, part of the reason I'm throwing this up here, despite the long list of answers, is to provide a little more all in one type solution and get some feed back in the future on how to expand it to include more real types.
With the following solution, as aforementioned, I combined a couple of solutions found here, as well as incorporate a fix for returning a value of jQuery on jQuery defined object if available. I also append the method to the native Object prototype. I know that is often taboo, as it could interfere with other such extensions, but I leave that to user beware. If you don't like this way of doing it, simply copy the base function anywhere you like and replace all variables of this with an argument parameter to pass in (such as arguments[0]).
;(function() { // Object.realType
function realType(toLower) {
var r = typeof this;
try {
if (window.hasOwnProperty('jQuery') && this.constructor && this.constructor == jQuery) r = 'jQuery';
else r = this.constructor && this.constructor.name ? this.constructor.name : Object.prototype.toString.call(this).slice(8, -1);
}
catch(e) { if (this['toString']) r = this.toString().slice(8, -1); }
return !toLower ? r : r.toLowerCase();
}
Object['defineProperty'] && !Object.prototype.hasOwnProperty('realType')
? Object.defineProperty(Object.prototype, 'realType', { value: realType }) : Object.prototype['realType'] = realType;
})();
Then simply use with ease, like so:
obj.realType() // would return 'Object'
obj.realType(true) // would return 'object'
Note: There is 1 argument passable. If is bool of true, then the return will always be in lowercase.
More Examples:
true.realType(); // "Boolean"
var a = 4; a.realType(); // "Number"
$('div:first').realType(); // "jQuery"
document.createElement('div').realType() // "HTMLDivElement"
If you have anything to add that maybe helpful, such as defining when an object was created with another library (Moo, Proto, Yui, Dojo, etc...) please feel free to comment or edit this and keep it going to be more accurate and precise. OR roll on over to the GitHub I made for it and let me know. You'll also find a quick link to a cdn min file there.
This version is a more complete one:
const typeOf = obj => {
let type = ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1]
if (type === 'Object') {
const results = (/^(function|class)\s+(\w+)/).exec(obj.constructor.toString())
type = (results && results.length > 2) ? results[2] : ''
}
return type.toLowerCase()
}
Now not only you can have these results: (as they've been answered here)
undefined or empty -> undefined
null -> null
NaN -> number
5 -> number
{} -> object
[] -> array
'' -> string
function () {} -> function
/a/ -> regexp
new Date() -> date
new Error -> error
Promise.resolve() -> promise
function *() {} -> generatorfunction
new WeakMap() -> weakmap
new Map() -> map
But also you can get the type of every instance or object you construct from classes or functions: (which is not valid between other answers, all of them return object)
class C {
constructor() {
this.a = 1
}
}
function F() {
this.b = 'Foad'
}
typeOf(new C()) // -> c
typeOf(new F()) // -> f
I guess the most universal solution here - is to check for undefined and null first, then just call constructor.name.toLowerCase().
const getType = v =>
v === undefined
? 'undefined'
: v === null
? 'null'
: v.constructor.name.toLowerCase();
console.log(getType(undefined)); // 'undefined'
console.log(getType(null)); // 'null'
console.log(getType('')); // 'string'
console.log(getType([])); // 'array'
console.log(getType({})); // 'object'
console.log(getType(new Set())); // `set'
console.log(getType(Promise.resolve())); // `promise'
console.log(getType(new Map())); // `map'
I've made this function:
( You should name it more unique so it doesn't collide with some other global name. )
function type(theThing) {
return Object.prototype.toString.call(theThing).match(/\s([\w]+)/)[1].toLowerCase()
}
type({}) //-> 'object'
type([]) //-> 'array'
type(function(){}) //-> 'function'
type(null) //-> 'null'
type(undefined) //-> 'undefined
type(true) //-> 'boolean'
type('hello') //-> 'string'
type(42) //-> 'number'
type(Symbol()) //-> 'symbol'
type(/abc/) //-> 'regexp'
type(new Set()) //-> 'set'
// etc ...
PS: F.NiX above made more robust version that also tell you the name of your custom objects made from Class or constructor function.
https://npmjs.com/package/advanced-type
I created a package for this purpose.
typeof condition is used to check variable type, if you are check variable type in if-else condition
e.g.
if(typeof Varaible_Name "undefined")
{
}

Can i use constructor.name to detect types in JavaScript

Can I use the "constructor" property to detect types in JavaScript?
Or is there something I should know about it.
For example: var a = {}; a.constructor.name; // outputs "Object"
or var b = 1; b.constructor.name; // outputs "Number"
or var d = new Date(); d.constructor.name; // outputs "Date" not Object
or var f = new Function(); f.constructor.name; // outputs "Function" not Object
only if use it on arguments arguments.constructor.name; //outputs Object like first example
I see quite often developers using: Object.prototype.toString.call([]) or
Object.prototype.toString.call({})
You can use typeof, but it returns misleading results sometimes. Instead, use Object.prototype.toString.call(obj), which uses the object's internal [[Class]] property. You can even make a simple wrapper for it, so it acts similar to typeof:
function TypeOf(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
TypeOf("String") === "string"
TypeOf(new String("String")) === "string"
TypeOf(true) === "boolean"
TypeOf(new Boolean(true)) === "boolean"
TypeOf({}) === "object"
TypeOf(function(){}) === "function"
Don't use obj.constructor because it be changed, although you might be able to use instanceof to see if it is correct:
function CustomObject() {
}
var custom = new CustomObject();
//Check the constructor
custom.constructor === CustomObject
//Now, change the constructor property of the object
custom.constructor = RegExp
//The constructor property of the object is now incorrect
custom.constructor !== CustomObject
//Although instanceof still returns true
custom instanceof CustomObject === true
You can use typeof
Ex: typeof("Hello")

Categories