Problem: Using JS to implement a clone () Cloning function, the function will enter the different types of values Number,string,undefined,boolean,function,null,object,array,regexp, Clone a copy.
First, the problem solving code
Direct Sticker Code,
functionClone (obj) {varcopy; Switch(typeofobj) { Case' Undefined ': Break; Case' Number ': Case' String ': Case' Boolean ': Case' function ': copy = obj; Break; Case' Object ': if(obj = =NULL) copy =NULL; Else if(Tostring.call (obj) = = = ' [Object Array] ') {Copy= []; for(varIinchobj) Copy.push (Clone (Obj[i)); } Else if(Tostring.call (obj) = = = ' [Object RegExp] ') {Copy=obj; } Else{Copy= {}; for(varJinchobj) copy[j]=Clone (Obj[j]); } } returncopy; } varA=undefined; varB=1; varC= "Hello"; varD=true; varAdd=function(A, b) {returnA +b; } varE=NULL; varf=[1,2,3]; varg=/^\s+/; varH={A:1, B:2} console.log (typeofClone (a)); Console.log (typeofClone (b)); Console.log (typeofClone (c)); Console.log (typeofClone (d)); Console.log (Clone (add) (The)); Console.log (Object.prototype.toString.call (Clone (e))); Console.log (Object.prototype.toString.call (Clone (f))); Console.log (Object.prototype.toString.call (Clone (g))); Console.log (Object.prototype.toString.call (Clone (h)));
Results:
Second, the question
When I first saw the problem, I thought that the result of [typeof] was, what to do, the regular expression, the Null,object typeof. Look at the code above, which is resolved with Object.prototype.toString.call (obj) or tostring.call (obj).
So why not just use obj.tostring ()? Let's take a look at what obj.tostring () will output.
Null and undefined actually went wrong, which is for sure, because ToString () cannot complete the transformation of null and undefined, using string () to
If string () is not converted to null or undefined, it is automatically converted to ToString (). It's far away. Let's get back to the chase.
So what is the result of using Object.prototype.toString.call (obj)?
It's not the same, what's going on?
It turns out that although array,null and other types are instances of object, they each rewrite the ToString () method, and we try to verify that:
var arr=[1,2,3];console.log (Array.prototype.hasOwnProperty ("toString")); // determine if the ToString () method is in the prototype Console.log (arr.tostring ()); Delete Array.prototype.toString; // Delete the overridden toStringConsole.log (Array.prototype.hasOwnProperty ("ToString")) in the Array prototype; Console.log ( Arr.tostring ());
Results:
It's obvious that it's been rewritten.
Third, there are some words
In fact, some people would say that you can use arr instanceof array to determine whether an array, in fact, instanceof in a cross-frame object built by the scene will be invalidated.
Some questions about JS's clone () function writing