权声明:本文为博主原创文章,未经博主允许不得转载。

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

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

typeof

  1. 在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 "object"。

ECMA 对Object.prototype.toString的解释

  1. Object.prototype.toString ( )
  2. When the toString method is called, the following steps are taken:
  3. If the this value is undefined, return "[object Undefined]".
  4. If the this value is null, return "[object Null]".
  5. Let O be the result of calling ToObject passing the this value as the argument.
  6. Let class be the value of the [[Class]] internal property of O.
  7. 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

  1. var oP = Object.prototype,
  2. toString = oP.toString;
  3. console.log(toString.call([123]));//[object Array]
  4. console.log(toString.call('123'));//[object String]
  5. console.log(toString.call({a: '123'}));//[object Object]
  6. console.log(toString.call(/123/));//[object RegExp]
  7. console.log(toString.call(123));//[object Number]
  8. console.log(toString.call(undefined));//[object Undefined]
  9. console.log(toString.call(null));//[object Null]
  10. //....
 // 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(H)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"H+": this.getHours(), //小时 --------*********仅支持24小时制**************
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}; //将指定的毫秒数加到此实例的值上
Date.prototype.addMilliseconds = function (value) {
var millisecond = this.getMilliseconds();
this.setMilliseconds(millisecond + value);
return this;
};
//将指定的秒数加到此实例的值上
Date.prototype.addSeconds = function (value) {
var second = this.getSeconds();
this.setSeconds(second + value);
return this;
};
//将指定的分钟数加到此实例的值上
Date.prototype.addMinutes = function (value) {
var minute = this.addMinutes();
this.setMinutes(minute + value);
return this;
};
//将指定的小时数加到此实例的值上
Date.prototype.addHours = function (value) {
var hour = this.getHours();
this.setHours(hour + value);
return this;
};
//将指定的天数加到此实例的值上
Date.prototype.addDays = function (value) {
var date = this.getDate();
this.setDate(date + value);
return this;
};
//将指定的星期数加到此实例的值上
Date.prototype.addWeeks = function (value) {
return this.addDays(value * 7);
};
//将指定的月份数加到此实例的值上
Date.prototype.addMonths = function (value) {
var month = this.getMonth();
this.setMonth(month + value);
return this;
};
//将指定的年份数加到此实例的值上
Date.prototype.addYears = function (value) {
var year = this.getFullYear();
this.setFullYear(year + value);
return this;
}; /**
* @ngdoc function
* @name sUndefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value) { return typeof value === 'undefined'; } /**
* @ngdoc function
* @name sDefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value) { return typeof value !== 'undefined'; } /**
* @ngdoc function
* @name sObject
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects. Note that JavaScript arrays are objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && typeof value === 'object';
} /**
* Determine if a value is an object with a null prototype
*
* @returns {boolean} True if `value` is an `Object` with a null prototype
*/
function isBlankObject(value) {
return value !== null && typeof value === 'object' && !getPrototypeOf(value);
} /**
* @ngdoc function
* @name sString
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value) { return typeof value === 'string'; } /**
* @ngdoc function
* @name sNumber
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Number`.
*
* This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
*
* If you wish to exclude these then you can use the native
* [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
* method.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value) { return typeof value === 'number'; } /**
* @ngdoc function
* @name sDate
* @module ng
* @kind function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value) {
return Object.prototype.toString.call(value) === '[object Date]';
} /**
* @ngdoc function
* @name sArray
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/ function isArray(value) {
return Object.prototype.toString.call(value) === '[object Array]';
} /**
* @ngdoc function
* @name sFunction
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value) { return typeof value === 'function'; } /**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return Object.prototype.toString.call(value) === '[object RegExp]';
} /**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.window === obj;
} function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
} function isFile(obj) {
return Object.prototype.toString.call(obj) === '[object File]';
} function isFormData(obj) {
return Object.prototype.toString.call(obj) === '[object FormData]';
} function isBlob(obj) {
return Object.prototype.toString.call(obj) === '[object Blob]';
} function isBoolean(value) {
return typeof value === 'boolean';
} function isNullOrEmpty(str) {
if (str && str.length > 0) {
return false;
}
return true;
} function trim(str)
{
return str.replace(/(^\s*)|(\s*$)/g, '');
} function ltrim(str)
{
return str.replace(/^\s*/g,'');
} function rtrim(str)
{
return str.replace(/\s*$/,'');
} function equals(str1, str2)
{
if(str1 == str2)
{
return true;
}
return false;
} function equalsIgnoreCase(str1, str2)
{
if(str1.toUpperCase() == str2.toUpperCase())
{
return true;
}
return false;
} function isChinese(str)
{
var str = str.replace(/(^\s*)|(\s*$)/g,'');
if (!(/^[\u4E00-\uFA29]*$/.test(str)
&& (!/^[\uE7C7-\uE7F3]*$/.test(str))))
{
return false;
}
return true;
} function isEmail(str)
{
if(/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str))
{
return true
}
return false;
} function isImg(str)
{
var objReg = new RegExp("[.]+(jpg|jpeg|swf|gif)$", "gi");
if(objReg.test(str))
{
return true;
}
return false;
} function isInteger(str)
{
if(/^-?\d+$/.test(str))
{
return true;
}
return false;
} function isFloat(str)
{
if(/^(-?\d+)(\.\d+)?$/.test(str))
{
return true;
}
return false;
} function isMobile(str)
{
if(/^1[35]\d{9}/.test(str))
{
return true;
}
return false;
} function isPhone(str)
{
if(/^(0[1-9]\d{1,2}-)\d{7,8}(-\d{1,8})?/.test(str))
{
return true;
}
return false;
} function isIP(str){
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])$/;
if(reg.test(str))
{
return true;
}
return false;
} function isDateTimeString(str)
{
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]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/;
if(reg.test(str))
{
return true;
}
return false;
}

【JavaScript】Object.prototype.toString.call()进行类型判断的更多相关文章

  1. Object.prototype.toString.call()进行类型判断

    为什么类型判断用到Object.prototype.toString.call()进行类型判断,而不用typeof()呢? 然后翻了一下资料: Typeof 在使用 ]));/));));//[obj ...

  2. 使用Object.prototype.toString.call()方法精确判断对象的类型

    在JavaScript里使用typeof判断数据类型,只能区分基本类型,即:number.string.undefined.boolean.object. 对于null.array.function. ...

  3. JavaScript:Object.prototype.toString方法的原理

    在JavaScript中,想要判断某个对象值属于哪种内置类型,最靠谱的做法就是通过Object.prototype.toString方法. var arr = []; console.log(Obje ...

  4. JavaScript:Object.prototype.toString进行数据类型判定

    在JavaScript中,想要判断某个对象值属于哪种内置类型,最靠谱的做法就是通过Object.prototype.toString方法. var arr = []; console.log(Obje ...

  5. js的深入学习课程Object.prototype.toString.call()

    1.通过 Object.prototype.toString.call() 进行类型判断 function isArray(obj) { return Object.prototype.toStrin ...

  6. JavaScript中toStirng()与Object.prototype.toString.call()方法浅谈

    toStirng()与Object.prototype.toString.call()方法浅谈 一.toString()是一个怎样的方法?它是能将某一个值转化为字符串的方法.然而它是如何将一个值从一种 ...

  7. Object.prototype.toString.call() 、 instanceof 以及 Array.isArray()判断数组的方法的优缺点

    1. Object.prototype.toString.call() 每一个继承 Object 的对象都有 toString 方法,如果 toString 方法没有重写的话,会返回 [Object ...

  8. toStirng()与Object.prototype.toString.call()方法浅谈

    一.toString()是一个怎样的方法?它是能将某一个值转化为字符串的方法.然而它是如何将一个值从一种类型转化为字符串类型的呢? 通过下面几个例子,我们便能获得答案: 1.将boolean类型的值转 ...

  9. Object.prototype.toString.call()方法浅谈

    使用Object.prototype上的原生toString()方法判断数据类型,使用方法如下: Object.prototype.toString.call(value) 1.判断基本类型: Obj ...

随机推荐

  1. linux中find指令与grep命令的组合使用

    linux下find与grep管道命令的组合使用: 一.使用find与grep 1. 查找所有".h"文件(非组合命令) find /PATH -name "*.h&qu ...

  2. [转]从数据库中导出用友U8的现存量数据到Excel表

    转载自:http://www.czerp.com.cn/page/Default.asp?ID=372 可通过Excel获取外部数据的方式与SQL数据库创建查询连接,并导入到Excel中: Selec ...

  3. WPF/ArcGIS Engine三维开发和EVC3/4升级到VS项目建议(转)

    系统环境:Windows 7 专业版,Visual Studio 2010,ArcGIS Engine 9.3 1.创建项目 创建一个WPF的项目,必须选择.Net framework 3.5(AE9 ...

  4. tr 替换删除字符

    1.关于tr    通过使用 tr,您可以非常容易地实现 sed 的许多最基本功能.您可以将 tr 看作为 sed 的(极其)简化的变体:它可以用一个字符来替换另一个字符,或者可以完全除去一些字符.您 ...

  5. 【转】在Eclipse中安装和使用TFS插件

    文章地址:http://www.cnblogs.com/judastree/archive/2012/09/05/2672640.html 问题: 在Eclipse中安装和使用TFS插件. 解决过程: ...

  6. grep, egrep, fgrep笔记

    grep, egrep, fgrep grep: 根据模式搜索文本,并将符合模式的文本行显示出来.Pattern: 文本字符和正则表达式的元字符组合而成匹配条件 grep [options] PATT ...

  7. [破解] DRM-内容数据版权加密保护技术学习(上):视频文件打包实现

    1. DRM介绍: DRM,英文全称Digital Rights Management, 可以翻译为:内容数字版权加密保护技术. DRM技术的工作原理是,首先建立数字节目授权中心.编码压缩后的数字节目 ...

  8. HibernateTemplate和HibernateDaoSupport

    Spring整合Hibernate后,为Hibernate的DAO提供了两个工具类:HibernateTemplate和HibernateDaoSupport HibernateTemplateHib ...

  9. Android学习总结——Content Provider

    原文地址:http://www.cnblogs.com/bravestarrhu/archive/2012/05/02/2479461.html Content Provider内容提供者 : and ...

  10. kettle工具同步数据乱码-Linux下乱码问题二

    将写好的kettle工程部署到Linux下后,同步的数据都成了乱码,幸运的是数据库有备份. 下面就说一下,kettle工程如何同步两端编码格式都是utf8的数据库. 我们只需要更改kettle数据库连 ...