Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the class name of an Object in Node JS

Question is very Simple. If you instance, for example, a Buffer you do:

b = new Buffer(0);

then you check the type:

typeof b;

The result is 'Object', but I want to know it is a Buffer.

If you made this in the node console you get it:

>b = new Buffer(1024);
>typeof b
'object'
> b
<Buffer ...>

So, some how the console knows that b is a Buffer.

like image 803
Pablo Avatar asked Aug 30 '14 21:08

Pablo


People also ask

How do you find the class name of an object?

If you have a JavaSW object, you can obtain it's class object by calling getClass() on the object. To determine a String representation of the name of the class, you can call getName() on the class.

How can we get name and type of any object?

Use the typeof operator to get the type of an object or variable in JavaScript. The typeof operator also returns the object type created with the "new" keyword. As you can see in the above example, the typeof operator returns different types for a literal string and a string object.

What is object class in JS?

The Object type represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities. Objects can be created using the Object() constructor or the object initializer / literal syntax.

How to get the class name of an object in JavaScript?

So, it’s easy for us to get the class name of an object in JavaScript using its constructor name. It doesn’t matter whether the constructor is a default constructor or you create it (the programmer); the constructor’s name will always be the same as its class name.

What is the difference between nodename and nodename in JavaScript?

If the node is an element node, the nodeName property will return the tag name. If the node is an attribute node, the nodeName property will return the name of the attribute. For other node types, the nodeName property will return different names for different node types.

How to get the name of the specified node in HTML?

More "Try it Yourself" examples below. The nodeName property returns the name of the specified node. If the node is an element node, the nodeName property will return the tag name. If the node is an attribute node, the nodeName property will return the name of the attribute.

How to get the class name of a constructor in Java?

the constructor has a property called name accessing that will give you the class name. function getClass (obj) { // if the type is not an object return the type let type = typeof obj if ( (type !== 'object')) { return type; } else { //otherwise, access the class using obj.constructor.name return obj.constructor.name; } }


1 Answers

In your case:

b = new Buffer(1024);
if (b instanceof Buffer) {
  ...

More generally, see this answer.

like image 136
mb21 Avatar answered Nov 04 '22 16:11

mb21