简体   繁体   中英

JavaScript instanceof: can't define what instance of function's argument is

I'm still learning JavaScript,reading books,utilizing FireBug,experimenting.

I'm amazed and stuck on thing below.

Have function declaration:

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

It's assumed,that it's varargs.

I call it like:

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

It's possible to get from argument value by calling:

args.from

The result of typeof args.from is number
That looks sane.
pay attention: number is in lower case

I am interested of what instance args.from is.
Actually, can't get its instance value.
tried:

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

It is not Number - very strange
It's not Object - quite strange
It's not String -that's OK
It 's not Boolean -that's OK
It's neither null nor 'undefined' - looks OK.

What is it?

That's a primitive numeric value.
It isn't an instance of any class.

instanceof can only return true on 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 .

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

As passed, from.to is a primitive type, so you can't call instanceof on it.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM