Javascript to get function _ javascript For variable type

Source: Internet
Author: User
In JavaScript, you sometimes need to know the type of a variable accurately. Obviously, the typeof function cannot meet this requirement. In most cases, this function returns an object. This function requires a bit of code to implement. The following function can get a variable type. When you call a variable, a variable type described in the string format will be returned.

The Code is as follows:


// Obtain the type of x, and return the type name.
Function getType (x ){
// If x is null, null is returned.
If (x = null) return "null ";
Var t = typeof x;
// If x is a simple type, the return type name
If (t. toLocaleLowerCase ()! = "Object") return t;
// Call the toString method of the object class to obtain the type information.
// The object. toString method returns information similar to this [object class name]
T = Object. prototype. toString. apply (x). toLowerCase ();
// Intercept the class name part returned by the toString Method
T = t. substring (8, t. length-1 );
If (t. toLocaleLowerCase ()! = "Object") return t;
// Check whether x is of the object Type
If (x. constructor = Object) return t;
// Obtain the type name from the constructor
If (typeof x. constructor = "function ")
Return getFunctionName (x. constructor );
Return "unknow type ";
}
// Obtain the function name
Function getFunctionName (fn ){
If (typeof fn! = "Function") throw "the argument must be a function .";
Var reg =/\ W * function \ s + ([\ w \ $] +) \ s *\(/;
Var name = reg.exe c (fn );
If (! Name ){
Return '(Anonymous )';
}
Return name [1];
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.