First, the constructor name gets
Each object has aConstructorproperty of each object.ConstructorProperty describes its constructor.
function Fn () {} var New The constructor property of the // True object describes its constructor
The Obj object used in the following code is the one created here
1. Usestring InterceptionGet constructor Name
//using string interception to getvarstr ="'+Obj.constructor;varSTR1 = Str.replace ('function','|');//replace function characters with | To facilitate interceptionvarStartIndex = Str1.indexof ('|');//Find string intercept start indexvarEndIndex = Str1.indexof ('(');//Find string intercept end indexif(StartIndex! =-1&& EndIndex! =-1 ){ varName = Str1.slice (startindex+2, EndIndex); Console.log (name);}2. UseRegular ExpressionsGet constructor Name
// using regular expressions to get var reg =/function (. +) \ (/; var name1 = reg.exec (str); Console.log (name1);
3. Using objectsName PropertyGet constructor Name
// Get constructorConsole.log (Obj.constructor.name) with the name attribute; // IE8 not supported below
Combined with the above 3 methods, theIE8 browser can only use string interception has been obtained by the regular expression method, and the advanced browser 3 methods are OK, it is necessary to perform the browser performance testing to make compatible
//compatible with all browsers get the constructor namefunctionGetfnname (FN) {/*if (typeof fn!== ' function ') return; Return fn.name? Fn.name:/function (. +) \ (/.exec (fn + ") [1]; */ /*if (typeof fn!== ' function ') return; return Fn.name | | /function (. +) \ (/.exec (fn + ") [1]; */ return typeoffn!== ' function '?Undefined:fn.name|| /function (. +) \ (/.exec (fn + ") [1];}functionPersonwu () {}varObj2 =NewPersonwu ();varName =Getfnname (Obj2.constructor); Console.log (name);//PersonwuSecond, the String method
var string = ' 123abc456 '; var i = 3//substring (startindex,length) = = substr usage same console.log ( String.substring (0,i)); // 123 Two parameters indicate starting from the left of the index value 0 to extract the first I character Console.log (string.substring (i)); // 456 If a parameter is passed from the left to the first intercept to the rightmost //Slice (startindex,enindex)Console.log ( String.slice (0,i)) // Pack left not pack right,-1 for right first bit //string.replace (REGEXP/SUBSTR, Replacement)
JavaScript Knowledge Rollup------methods and string handling methods for getting constructor names