I used a lot of Javascript frameworks and occasionally looked at the framework's source code. I often saw such code.
The Code is as follows:
IsArray: function (v ){
Return toString. apply (v) ===' [object Array] ';
},
IsDate: function (v ){
Return toString. apply (v) ===' [object Date] ';
},
IsObject: function (v ){
Return !! V & Object. prototype. toString. call (v) = '[object Object]';
},
IsPrimitive: function (v ){
Return Ext. isString (v) | Ext. isNumber (v) | Ext. isBoolean (v );
},
IsFunction: function (v ){
Return toString. apply (v) ===' [object Function] ';
},
IsNumber: function (v ){
Return typeof v === 'number' & isFinite (v );
},
IsString: function (v ){
Return typeof v = 'string ';
},
IsBoolean: function (v ){
Return typeof v = 'boolean ';
}
The above is Extjs3.X ext-base.js inside the judgment type code, you have a careful look, will find that there are a lot of the same thing, such:
The Code is as follows:
Is type: function (v ){
Return toString. apply (v) = "type ";
}
Or
Is type: function (v ){
Returntypeof v = "type ";
}
However, we can use the toString method to determine the type of tyoeof. All the above Code can be of the same type, that is:
The Code is as follows:
Var is type = function (v ){
Return toString. call (v) = "type ";
}
The above is a model. The method corresponding to this judgment is a method in the body. We can simplify it (but there is a drawback: Poor readability), which can greatly reduce the code, this improves Javascript loading efficiency. The improved code is as follows:
The Code is as follows:
Var Easy = {}, dataTypes = ["Number", "Boolean", "String", "Array ",
"Object", "Function", "Date", "RegExp"];
Var toStr = Object. prototype. toString;
Var is = function (v, t ){
Return toStr (o) = "[object" + t + "]";
};
For (var I = 0, len = dataTypes. length, t; I <len; I ++ ){
(Function (t ){
Easy ["is" + t] = function (o ){
Return is (o, t );
}
}) (DataTypes [I]); // the closure is used.
}
In the above Code, we have created eight methods for determining the type starting with "is" for the Easy object. Of course, if some methods are unreasonable, We can overwrite them as follows:
The Code is as follows:
Easy. isNumber = function (v ){
Return toString. call (v) === "[object Number]" & isFinite (v );
}
So sometimes you can write some methods with similar functions to consider this writing method. If you are hungry and have a meal, I will introduce it here. I will talk about it later.