Just curious:
- 4 instanceof Number => false
- new Number(4) instanceof Number => true?
Why is this? Same with strings:
'some string' instanceof String
returns falsenew String('some string') instanceof String
=> trueString('some string') instanceof String
also returns false('some string').toString instanceof String
also returns false
For object, array or function types the instanceof operator works as expected. I just don't know how to understand this.
[re-opened to share new insights]
After testing I cooked up this functionality to be able to retrieve the type of any javascript object (be it primitive or not):
Object.prototype.typof = objType;
objType.toString = function(){return 'use [obj].typof()';};
function objType() {
var inp = String(this.constructor),
chkType = arguments[0] || null,
val;
function getT() {
return (inp.split(/\({1}/))[0].replace(/^\n/,'').substr(9);
}
return chkType
? getT().toLowerCase() === chkType.toLowerCase()
: getT();
}
Now you can check any type like this:
var Newclass = function(){}; //empty Constructor function
(5).typof(); //=> Number
'hello world'.typof(); //=> String
new Newclass().typof(); //=> Newclass
Or test if an object is of some type:
(5).typof('String'); //=> false
new Newclass().typof('Newclass') //=> true
[].typof('Arrray'); //=> true;