typeof(最基本的)
typeof 只能檢查出來以下7幾種類型:
- Undefined ————“undefined”
- Null ————“object” (見下方)
- 布爾值 ————“boolean”
- 數值 ————“number”
- 字符串 ————“string”
- 函數對象 (implements [[Call]] in ECMA-262 terms) ————“function”
- 任何其他對象 ————“object”
console.log(typeof a); //'undefined'
console.log(typeof(true)); //'boolean'
console.log(typeof '123'); //'string'
console.log(typeof 123); //'number'
console.log(typeof NaN); //'number'
console.log(typeof null); //'object'
var obj = new String();
console.log(typeof(obj)); //'object'
var fn = function(){};
console.log(typeof(fn)); //'function'
console.log(typeof(class c{})); //'function'
console.log(typeof(new Boolean(0)));//object
Object.prototype.toString.call()
var a = "hello world";
var b = [];
var c = function(){};
console.log( Object.prototype.toString.call( a ) );
console.log( Object.prototype.toString.call( b ) );
console.log( Object.prototype.toString.call( c ) );
//結果
[object String];
[object Array];
[object Function];
instanceof
functionPerson(){};
functionStudent(){};
var p =new Person();
Student.prototype=p;//繼承原型
var s=new Student();
console.log(s instanceof Student);//trueconsole.log(s instanceof Person);//true