分析$.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

posted @ 2014-05-13 14:45  走走停停走走  Views(371)  Comments(0Edit  收藏  举报