Learn to use the advanced security type detection function

js built-in type detecting mechanism is not completely reliable, such typeof operator, fourth edition Safari until at regular expression typeof operator returns the application function, it is difficult to determine the function is not a value in the end.

Another example instanceof operator is also in a lot of problems in the presence of a plurality of global scope (like a page comprises a plurality of frame). such as

let isArray = value instanceof Array;

The above code to return true, value must be an array, and must be the same, and a constructor Array opera scope. (Remember, Array is the window attributes.) If the value in the array is defined in another one frame, then the above code will return false.

The method of solving the above problems are the same. As we all know, call the Object toString native on any value () method returns a [object NativeConstructorName] string format. Within each class has a [[class]] property. In this attribute to specify the configuration of the character string of the function name.

alert(Object.prototype.toString.call(value));   //[object Array]

Since the name of the constructor and the play regardless of the scope of the original array, thus using toString () to ensure the return consistent value.

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]'; } 

Native JSON object detection. Object of toString () constructor method can not detect non-native name constructor. Thus, any constructors are defined by the developer will be returned [object Object]

let isNativeJSON = window.JSON && Object.prototype.toString.call(JSON) == "[object JSON]"

Scan code plus group, daily updates an article front-end technology to grow together.

Guess you like

Origin www.cnblogs.com/bbqq1314/p/12545473.html
Recommended