Background: know js built-in type detection, most cases are less reliable, such as: typeof, instanceof
typeof a return type operand uncalculated, can be found in all objects are returned object (null i.e. null object pointer is null)
the instanceof: anywhere prototype for testing the properties appear in the constructor of the object in the prototype chain (simple to understand: detecting whether an object can be found in the left along the chain is equal to the position of the prototype prototype constructor property right) will be attached later the simulation method.
Disadvantages:
1, instanceof a relationship with a global scope, [] instanceof window.frames[0].Array
will return false
, because Array.prototype !== window.frames[0].Array.prototype
2, Object derived subclasses are of Obejct [] instanceof Array [] instanceof Object is true
instanceof analog implementation:
1 function instanceOf(left, right) { 2 let leftValue = left.__proto__ 3 let rightValue = right.prototype 4 console.log(leftValue,rightValue) 5 while (true) { 6 if (leftValue === null) { 7 return false 8 } 9 if (leftValue === rightValue) { 10 return true 11 } 12 leftValue = leftValue.__proto__ 13 } 14 } 15 16 let a = {}; 17 18 console.log(instanceOf(a, Array))
Security type detection methods:
BACKGROUND: Object value on any call native of toString () method returns a [object NativeConstructorName] format string.
NativeConstructorName ===> Native constructor name (that is, its father's name, not the grandfather (Object) name)
function isArray(value){ return Object.prototype.toString.call(value) == "[object Array]"; } function isFunction(value){ return Object.prototype.toString.call(value) == "[object Function]"; } function isRegExp(value){ return Object.prototype.toString.call(value) == "[object RegExp]"; }
Why toString method with a direct instance of an object not? This is because in the other constructors, the toString method has been rewritten. For example: [1,2] .toString () ===> "1,2"