分析$.isPlainObject

作者:zccst

本次学习$.isPlainObject,是不是一个普通对象。测试对象是否是纯粹的对象(通过 "{}" 或者 "new Object" 创建的)

1,使用场景:

var o = {};

console.log($.isPlainObject(o));//如果是空对象就返回TRUE,否则返回FALSE。



2,下面看一下源码实现:

isPlainObject: function( obj ) {
// Not plain objects:以下三种情况不是普通对象(1)使用typeof判断;(2)DOM节点(3)window
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}

// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
       //obj的构造函数为真,且obj构造函数的原型对象里没有isPrototypeOf属性,则也不是纯粹的对象
if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}

// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
}



判断过程:
var class2type = {};
var core_hasOwn = class2type.hasOwnProperty;
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

core_hasOwn.call( o.constructor.prototype, "isPrototypeOf" )与
o.constructor.prototype.hasOwnProperty( "isPrototypeOf" )是相同的

hasOwnProperty语法:obj.hasOwnProperty(prop) //返回值就是TRUE或FALSE


如果您觉得本文的内容对您的学习有所帮助,您可以微信:
[img]http://dl2.iteye.com/upload/attachment/0109/0668/fb266dfa-95ca-3d09-b41e-5f04a19ba9a1.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值