JavaScript instanceof: cannot determine which instance of function argument

I am still learning JavaScript, reading books using FireBug, experimenting.

I am amazed and stuck on the things below.

Have a feature declaration:

var t = function (args){ ... } 

He suggested that he varargs.

I call it this way:

 <body onload="t({to:100,from:0})"> 

It is possible to get the value of the from argument by calling:

 args.from 

The result of typeof args.from is number
It looks great.
note: number is lowercase

I'm interested in the args.from example.
In fact, it is impossible to get the value of your instance.
tried:

 args.from instanceof Number args.from instanceof String args.from instanceof Object args.from instanceof Boolean 

This is not number - very strange This is not Object - rather strange This is not String that is OK
It's not a boolean - that's OK
This is neither null nor 'undefined' - it looks fine.

What is it?

+4
source share
2 answers

This is a primitive numeric value.
This is not an instance of any class.

instanceof can return true only objects (for which typeof returns "object" or "function" ).

This has nothing to do with the args object; you can get the same falsity from 4 instanceof Number .

In contrast, new Number(4) is an object wrapping primitive 4 , so typeof new Number(4) === "object and new Number(4) instanceof Number === true

+5
source

As transmitted, from.to is a primitive type, so you cannot call it instanceof .

If you really want to use instanceof instead of typeof , wrap it in Object :

 var from = Object(args.from); alert(from instanceof Number); // true! 
+2
source

Source: https://habr.com/ru/post/1387742/


All Articles