6

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.

MightyPork
  • 18,270
  • 10
  • 79
  • 133
Pablo
  • 456
  • 2
  • 7
  • 18
  • 1
    possible duplicate of [How do I get the name of an object's type in JavaScript?](http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript) – mb21 Aug 30 '14 at 21:22
  • 1
    Note: [`Buffer.isBuffer()`](http://nodejs.org/api/buffer.html#buffer_class_method_buffer_isbuffer_obj) and (in 0.11+) [`util.isBuffer()`](https://github.com/joyent/node/blob/v0.11.13/lib/util.js#L581-L584). – Jonathan Lonowski Aug 30 '14 at 21:28
  • 1
    @maximkou Good answer, but it's part of Ecmascript 6 and therefor not universally supported. Also fails on `var Apple = function() {}`. – Bart Aug 30 '14 at 21:33
  • 1
    @Bart, `var Apple = function() {}`, yes but this is a good starting point for @user3242467. I think using `instanceOf` is not a better solution for some situations. – maximkou Aug 30 '14 at 21:37
  • @Bart With the mention of [tag:nodejs], cross-browser/-engine support may not be a concern (though is still good to mention) and V8 has supported `function.name` despite it being so far unofficial. Also, in the case of `Apple`, the constructor itself is anonymous, so the console wouldn't show a name either. `console.log(new Apple()) // {}` – Jonathan Lonowski Aug 30 '14 at 21:43
  • @JonathanLonowski Buffer can be used in browsers using browserify. Also, even though Buffer is used as an example, the question is a generic question, and `b instanceof Buffer` is the most correct generic answer. Also note that `Buffer.isBuffer` uses `util.isBuffer`, which in turn simply checks if `arg instanceof Buffer`... – Bart Aug 30 '14 at 21:49

1 Answers1

12

In your case:

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

More generally, see this answer.

Community
  • 1
  • 1
mb21
  • 34,845
  • 8
  • 116
  • 142