js の typeof を調べた
すこし、思うところがあり、調べておいた。
| 判別式 | 結果 |
|---|---|
| typeof 1 | 'number' |
| typeof "aaa" | 'string' |
| typeof 0 | 'number' |
| typeof null | 'object' |
| typeof undefined | 'undefined' |
| typeof "" | 'string' |
| typeof false | 'boolean' |
| typeof true | 'boolean' |
| typeof [] | 'object' |
| typeof {} | 'object' |
| typeof function(){} | 'function' |
| typeof (function(){}) | 'function' |
| typeof new (function(){}) | 'object' |
| typeof Date | 'function' |
| typeof Array | 'function' |
| typeof Array.prototype | 'object' |
| typeof NaN | 'number' |
| typeof Infinity | 'number' |
| typeof Error | 'function' |
| typeof Math | 'object' |
| typeof RegExp | 'function' |
| typeof /aaa/ | 'object' |
| typeof Promise | 'function' |
| typeof Function | 'function' |
| typeof Function() | 'function' |
| typeof Function() () | 'undefined' |
| typeof new Function | 'function' |
| typeof new (new Function) | 'object' |
function とオブジェクトの境界線
typeof (function(){}) //=> function
typeof new (function(){}) //=> object
typeof new (new Function) //-> object
function は new 出来るしコンストラクタとして動作するので、 ここが境界線
new するとプロトタイプになるので
typeof Array //=>"function" typeof Array.prototype //=>"object"
このあたりもおもしろい。ここから分かる通り、コンストラクタのprototypeには インスタンスを入れる。
function Human(name){ this.name = name this.say = function(){ console.log(this.name)} } function Lady(name){ Human.call(this,name) } Lady.prototype = new Human a =new Lady('yuri') a.say()
こうやってみると、 nunber/ object / function /string / undefined / boolean くらいしか無いのがよく分かる。
null って object だけど、 toString出来ないんだよね不思議
function は全て new 出来るコンストラクタとして動作する。
MDNによると基本的なプリミティブな型は次の通り
- Boolean
- Null
- Undefined
- Number
- String
- Symbol (ES6)
- Object
あれ。function ってプリミティブ型じゃないんだ。。。
参考資料
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures