【JavaScript】Object.prototype.toString.call()进行类型判断

[javascript] view plain copy
 
 print?
  1.    op = Object.prototype,  
  2.    ostring = op.toString,  
  3. ...  
  4.   
  5. function isFunction(it) {  
  6.         return ostring.call(it) === '[object Function]';  
  7.     }  
  8.   
  9.     function isArray(it) {  
  10.         return ostring.call(it) === '[object Array]';  
  11.     }  

最近在看requireJS的源码时,看到上面一段代码,很是好奇,为啥进行类型判断时使用Object.prototype.toString? 如果是我的话就直接用typeof得了,后来查阅了一些资料:

typeof

[plain] view plain copy
 
 print?
  1. 在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 "object"。  
ECMA 对Object.prototype.toString的解释
[plain] view plain copy
 
 print?
  1. Object.prototype.toString ( )  
  2.   
  3. When the toString method is called, the following steps are taken:  
  4.   
  5. If the this value is undefined, return "[object Undefined]".  
  6. If the this value is null, return "[object Null]".  
  7. Let O be the result of calling ToObject passing the this value as the argument.  
  8. Let class be the value of the [[Class]] internal property of O.  
  9. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".  

http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2

[javascript] view plain copy
 
 print?
  1. var oP = Object.prototype,  
  2. toString = oP.toString;  
  3.   
  4. console.log(toString.call([123]));//[object Array]  
  5. console.log(toString.call('123'));//[object String]  
  6. console.log(toString.call({a: '123'}));//[object Object]  
  7. console.log(toString.call(/123/));//[object RegExp]  
  8. console.log(toString.call(123));//[object Number]  
  9. console.log(toString.call(undefined));//[object Undefined]  
  10. console.log(toString.call(null));//[object Null]  
  11. //....  
  1 // 对Date的扩展,将 Date 转化为指定格式的String
  2 // 月(M)、日(d)、小时(H)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
  3 // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
  4 // 例子: 
  5 // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
  6 // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
  7 Date.prototype.Format = function (fmt) {
  8     var o = {
  9         "M+": this.getMonth() + 1, //月份 
 10         "d+": this.getDate(), //
 11         "H+": this.getHours(), //小时 --------*********仅支持24小时制**************
 12         "m+": this.getMinutes(), //
 13         "s+": this.getSeconds(), //
 14         "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
 15         "S": this.getMilliseconds() //毫秒 
 16     };
 17     if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
 18     for (var k in o)
 19         if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
 20     return fmt;
 21 };
 22 
 23 //将指定的毫秒数加到此实例的值上 
 24 Date.prototype.addMilliseconds = function (value) {
 25     var millisecond = this.getMilliseconds();
 26     this.setMilliseconds(millisecond + value);
 27     return this;
 28 };
 29 //将指定的秒数加到此实例的值上 
 30 Date.prototype.addSeconds = function (value) {
 31     var second = this.getSeconds();
 32     this.setSeconds(second + value);
 33     return this;
 34 };
 35 //将指定的分钟数加到此实例的值上 
 36 Date.prototype.addMinutes = function (value) {
 37     var minute = this.addMinutes();
 38     this.setMinutes(minute + value);
 39     return this;
 40 };
 41 //将指定的小时数加到此实例的值上 
 42 Date.prototype.addHours = function (value) {
 43     var hour = this.getHours();
 44     this.setHours(hour + value);
 45     return this;
 46 };
 47 //将指定的天数加到此实例的值上 
 48 Date.prototype.addDays = function (value) {
 49     var date = this.getDate();
 50     this.setDate(date + value);
 51     return this;
 52 };
 53 //将指定的星期数加到此实例的值上 
 54 Date.prototype.addWeeks = function (value) {
 55     return this.addDays(value * 7);
 56 };
 57 //将指定的月份数加到此实例的值上 
 58 Date.prototype.addMonths = function (value) {
 59     var month = this.getMonth();
 60     this.setMonth(month + value);
 61     return this;
 62 };
 63 //将指定的年份数加到此实例的值上 
 64 Date.prototype.addYears = function (value) {
 65     var year = this.getFullYear();
 66     this.setFullYear(year + value);
 67     return this;
 68 };
 69 
 70 
 71 /**
 72  * @ngdoc function
 73  * @name sUndefined
 74  * @module ng
 75  * @kind function
 76  *
 77  * @description
 78  * Determines if a reference is undefined.
 79  *
 80  * @param {*} value Reference to check.
 81  * @returns {boolean} True if `value` is undefined.
 82  */
 83 function isUndefined(value) { return typeof value === 'undefined'; }
 84 
 85 
 86 /**
 87  * @ngdoc function
 88  * @name sDefined
 89  * @module ng
 90  * @kind function
 91  *
 92  * @description
 93  * Determines if a reference is defined.
 94  *
 95  * @param {*} value Reference to check.
 96  * @returns {boolean} True if `value` is defined.
 97  */
 98 function isDefined(value) { return typeof value !== 'undefined'; }
 99 
100 
101 /**
102  * @ngdoc function
103  * @name sObject
104  * @module ng
105  * @kind function
106  *
107  * @description
108  * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
109  * considered to be objects. Note that JavaScript arrays are objects.
110  *
111  * @param {*} value Reference to check.
112  * @returns {boolean} True if `value` is an `Object` but not `null`.
113  */
114 function isObject(value) {
115     // http://jsperf.com/isobject4
116     return value !== null && typeof value === 'object';
117 }
118 
119 
120 /**
121  * Determine if a value is an object with a null prototype
122  *
123  * @returns {boolean} True if `value` is an `Object` with a null prototype
124  */
125 function isBlankObject(value) {
126     return value !== null && typeof value === 'object' && !getPrototypeOf(value);
127 }
128 
129 
130 /**
131  * @ngdoc function
132  * @name sString
133  * @module ng
134  * @kind function
135  *
136  * @description
137  * Determines if a reference is a `String`.
138  *
139  * @param {*} value Reference to check.
140  * @returns {boolean} True if `value` is a `String`.
141  */
142 function isString(value) { return typeof value === 'string'; }
143 
144 
145 /**
146  * @ngdoc function
147  * @name sNumber
148  * @module ng
149  * @kind function
150  *
151  * @description
152  * Determines if a reference is a `Number`.
153  *
154  * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
155  *
156  * If you wish to exclude these then you can use the native
157  * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
158  * method.
159  *
160  * @param {*} value Reference to check.
161  * @returns {boolean} True if `value` is a `Number`.
162  */
163 function isNumber(value) { return typeof value === 'number'; }
164 
165 
166 /**
167  * @ngdoc function
168  * @name sDate
169  * @module ng
170  * @kind function
171  *
172  * @description
173  * Determines if a value is a date.
174  *
175  * @param {*} value Reference to check.
176  * @returns {boolean} True if `value` is a `Date`.
177  */
178 function isDate(value) {
179     return Object.prototype.toString.call(value) === '[object Date]';
180 }
181 
182 
183 /**
184  * @ngdoc function
185  * @name sArray
186  * @module ng
187  * @kind function
188  *
189  * @description
190  * Determines if a reference is an `Array`.
191  *
192  * @param {*} value Reference to check.
193  * @returns {boolean} True if `value` is an `Array`.
194  */
195 
196 
197 function isArray(value) {
198     return Object.prototype.toString.call(value) === '[object Array]';
199 }
200 
201 /**
202  * @ngdoc function
203  * @name sFunction
204  * @module ng
205  * @kind function
206  *
207  * @description
208  * Determines if a reference is a `Function`.
209  *
210  * @param {*} value Reference to check.
211  * @returns {boolean} True if `value` is a `Function`.
212  */
213 function isFunction(value) { return typeof value === 'function'; }
214 
215 
216 /**
217  * Determines if a value is a regular expression object.
218  *
219  * @private
220  * @param {*} value Reference to check.
221  * @returns {boolean} True if `value` is a `RegExp`.
222  */
223 function isRegExp(value) {
224     return Object.prototype.toString.call(value) === '[object RegExp]';
225 }
226 
227 
228 /**
229  * Checks if `obj` is a window object.
230  *
231  * @private
232  * @param {*} obj Object to check
233  * @returns {boolean} True if `obj` is a window obj.
234  */
235 function isWindow(obj) {
236     return obj && obj.window === obj;
237 }
238 
239 
240 function isScope(obj) {
241     return obj && obj.$evalAsync && obj.$watch;
242 }
243 
244 
245 function isFile(obj) {
246     return Object.prototype.toString.call(obj) === '[object File]';
247 }
248 
249 
250 function isFormData(obj) {
251     return Object.prototype.toString.call(obj) === '[object FormData]';
252 }
253 
254 
255 function isBlob(obj) {
256     return Object.prototype.toString.call(obj) === '[object Blob]';
257 }
258 
259 
260 function isBoolean(value) {
261     return typeof value === 'boolean';
262 }
263 
264 
265 function isNullOrEmpty(str) {
266     if (str && str.length > 0) {
267         return false;
268     }
269     return true;
270 }
271 
272 function trim(str)     
273 {     
274     return str.replace(/(^s*)|(s*$)/g, '');     
275 }     
276     
277     
278 function ltrim(str)     
279 {     
280     return str.replace(/^s*/g,'');     
281 }     
282     
283     
284 function rtrim(str)     
285 {     
286     return str.replace(/s*$/,'');     
287 }     
288     
289     
290     
291 function equals(str1, str2)     
292 {     
293     if(str1 == str2)     
294     {     
295         return true;     
296     }     
297     return false;     
298 }     
299     
300     
301 function equalsIgnoreCase(str1, str2)     
302 {     
303     if(str1.toUpperCase() == str2.toUpperCase())     
304     {     
305         return true;     
306     }     
307     return false;     
308 }     
309     
310     
311 function isChinese(str)     
312 {     
313     var str = str.replace(/(^s*)|(s*$)/g,'');     
314     if (!(/^[u4E00-uFA29]*$/.test(str)     
315             && (!/^[uE7C7-uE7F3]*$/.test(str))))     
316     {     
317         return false;     
318     }     
319     return true;     
320 }     
321     
322     
323 function isEmail(str)     
324 {     
325     if(/^[w-]+(.[w-]+)*@[w-]+(.[w-]+)+$/.test(str))     
326     {     
327         return true    
328     }     
329     return false;     
330 }     
331     
332     
333 function isImg(str)     
334 {     
335     var objReg = new RegExp("[.]+(jpg|jpeg|swf|gif)$", "gi");     
336     if(objReg.test(str))     
337     {     
338         return true;     
339     }     
340     return false;     
341 }     
342     
343     
344 function isInteger(str)     
345 {     
346     if(/^-?d+$/.test(str))     
347     {     
348         return true;     
349     }     
350     return false;     
351 }     
352     
353     
354 function isFloat(str)     
355 {     
356     if(/^(-?d+)(.d+)?$/.test(str))     
357     {     
358         return true;     
359     }     
360     return false;     
361 }     
362     
363     
364     
365 function isMobile(str)     
366 {     
367     if(/^1[35]d{9}/.test(str))     
368     {     
369         return true;     
370     }     
371     return false;     
372 }     
373     
374     
375 function isPhone(str)     
376 {     
377     if(/^(0[1-9]d{1,2}-)d{7,8}(-d{1,8})?/.test(str))     
378     {     
379         return true;     
380     }     
381     return false;     
382 }     
383     
384 function isIP(str){     
385     var reg = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/;     
386     if(reg.test(str))     
387     {     
388         return true;     
389     }     
390     return false;     
391 }     
392     
393     
394 function isDateTimeString(str)     
395 {     
396     var reg = /^((((1[6-9]|[2-9]d)d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]d|3[01]))|(((1[6-9]|[2-9]d)d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]d|30))|(((1[6-9]|[2-9]d)d{2})-0?2-(0?[1-9]|1d|2[0-8]))|(((1[6-9]|[2-9]d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/;     
397     if(reg.test(str))     
398     {     
399         return true;     
400     }     
401     return false;       
402 }     
403     
原文地址:https://www.cnblogs.com/micro-chen/p/5390116.html