JavaScript type check memo
instanceof
check whether an object belongs to a certain class
a = new Number('1'); // create a Number object using Number() constructor
b = Number('1'); // create primitive type object number using Number() function
a instanceof Number
> true // a is Number object
b instanceof Number
> false // b is primitive type object: number
typeof(a);
> 'object'
typeof(b);
> 'number'
prototype chain :
Number.prototype;
> [Number: 0]
a.__proto__;
> [Number: 0] // Number.prototype
a.__proto__.__proto__;
> {} // Object.prototype
a.__proto__.__proto__.__proto__;
> null // no deeper prototype
isPrototypeOf
a instanceof Class
can be rephrased as Class.prototype.isPrototypeOf(a)
a = new Number('1');
b = Number('1');
Number.prototype.isPrototypeOf(a)
> true
Number.prototype.isPrototypeOf(b)
> false
getOwnPropertyNames
Object.getOwnPropertyNames(Object)
[ 'length',
'name',
'prototype', // the instance of any Object follows this
'assign',
'getOwnPropertyDescriptor',
'getOwnPropertyDescriptors',
'getOwnPropertyNames', // use this to check properties
...
'keys',
'entries',
'values' ]
> Object.getOwnPropertyNames(Object.prototype)
[ 'constructor',
'__defineGetter__',
...
'propertyIsEnumerable',
'toString', // prototype.toString just return '[object <object name>]'
'valueOf',
'__proto__',
'toLocaleString' ]
Object.getOwnPropertyNames(Number)
[ 'length',
'name',
'prototype',
'isFinite',
...
'EPSILON' ]
Object.getOwnPropertyNames(Number.prototype)
[ 'constructor',
...
'toString',
'valueOf',
'toLocaleString' ]
prototype
Object.getPrototypeOf(123) // prototype of Number
> [Number: 0]
Object.getPrototypeOf('123') // prototype of String
> [String: '']
Object.getPrototypeOf([1,2,3]) // prototype of Array
> []
Object.prototype.toString.call(new Object())
> '[object Object]'
Object.prototype.toString.call(123)
> '[object Number]'
Object.prototype.toString.call('123')
> '[object String]'
Object.prototype.toString.call([1,2,3])
> '[object Array]'
String.prototype.toString.call('123') // String('123').toString()
> '123'
String.prototype.toString.call(123)
/* TypeError: String.prototype.toString requires that 'this' be a String
at Number.toString (<anonymous>) */
Number.prototype.toString.call(123) // Number(123).toString()
> '123'
Number.prototype.toString.call('123')
/* TypeError: Number.prototype.toString requires that 'this' be a Number
at String.toString (<anonymous>) */