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

  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. javascript prototype __proto__区别

    An Object's __proto__ property references the same object as its internal [[Prototype]] (often refer ...

  2. javascript之对象

    一.创建对象 1.对象直接量. var point = { x:0,y:0 }; //point就是一个对象,跟C#不同,它不需要一定有类才能创建对象. 2.通过new创建对象 var d = new ...

  3. codecomb 2092【课程选择】

    题目描述 大学选课总是烦恼着很多人.现在X同学选出了很多备选课,但是有的课程之间是有时间冲突的.X不会分身,自然无法在同一个时间上不同的课.每个课可能有很多备选时间,但是每个课只需要选一个时间上就可以 ...

  4. PCRE-正则库及用法

    摘自http://blog.chinaunix.net/uid-26575352-id-3517146.html    在C语言中利用PCRE实现正则表达式 http://www.pcre.org/ ...

  5. hdu 5465 Clarke and puzzle(前缀和,异或,nim博弈)

    Problem Description Clarke is a patient with multiple personality disorder. One day, Clarke split in ...

  6. cocos2dx lua 学习笔记(二)

    安装开发环境 sublime - http://www.sublimetext.com/2 package control - http://packagecontrol.io/installatio ...

  7. Java程序员面试题集(71-85)(转)

    转:http://blog.csdn.net/jackfrued/article/details/17566627 Java程序员面试题集(71-85) 摘要:这一部分主要包括了UML(统一建模语言) ...

  8. Android应用程序中的多个Activity的显示创建和调用

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTkzNjE0Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQk ...

  9. Lua多重继承

    http://blog.csdn.net/ssihc0/article/details/7742421 代码收藏了,以后用的到 --多重继承 local function search(k,plist ...

  10. CATransform3D参数的意义

    经常忘记CATransform3D各参数的意思,记下来好好理解下   struct CATransform3D { CGFloat m11(x缩放),m12(y切变),m13(旋转),m14(); C ...