isPlainObject的解释

参考: http://www.365mini.com/page/jquery_isplainobject.htm

先来看下使用案例:

//在当前页面内追加换行标签和指定的HTML内容
    function w(html) {
        document.body.innerHTML += "<br/>" + html;
    }
    w($.isPlainObject({})); // true
    w($.isPlainObject(new Object())); // true
    w($.isPlainObject({ name: "CodePlayer" })); // true
    w($.isPlainObject({ sayHi: function () { } })); // true


    w($.isPlainObject("CodePlayer")); // false
    w($.isPlainObject(true)); // false
    w($.isPlainObject(12)); // false
    w($.isPlainObject([])); // false
    w($.isPlainObject(function () { })); // false
    w($.isPlainObject(document.location)); // false(在IE中返回true)

    function Person() {
        this.name = "张三";
    }
    w($.isPlainObject(new Person())); // false

在jquery-19.1.1源码中,isPlainObject:

函数用于判断指定参数是否是一个纯粹的对象

所谓"纯粹的对象",就是该对象是通过"{}"或"new Object"创建的。

isPlainObject: function( obj ) {
        // Must be an Object.
        // Because of IE, we also have to check the presence of the constructor property.
        // Make sure that DOM nodes and window objects don't pass through, as well
        if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
            return false;
        }

        try {
            // Not own constructor property must be Object
            if (obj.constructor &&
                //20170609 huanhua 构造器在对象的原型上
                !core_hasOwn.call(obj, "constructor") &&
                //20170609 huanhua 以 new Object()或者{} 创建的对象,原型下 存在 isPrototypeOf 这个方法
                //其它方式创建的对象,原型下没isPrototypeOf这个方法,原型链的顶端有。此处解释见 代码01
                !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
                return false;
            }
        } catch ( e ) {
            // IE8,9 Will throw exceptions on certain host objects #9897
            return false;
        }

        // Own properties are enumerated firstly, so to speed up,
        // if last one is own, then all properties are own.

        var key;
        for ( key in obj ) {}
        //20170609 huanhua 当obj={}或者obj=new Object()时, key 就是 undefined 
        //当obj={ name:123 }这种格式时,最后一个key就是 name,如果不是这种格式的最后一个key就是原型链中的属性
        return key === undefined || core_hasOwn.call( obj, key );
    }

如下代码 01 :  用来解释代码   !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") :

var gf = new Object();//见 图1
    var ffh = { name: 123 };//见 图2
    var Person = function () {this.age = 45;} //见 图3
    console.log(gf);
    console.log(ffh);
    console.log(new Person());

图1

图2

图3

没写完,晚上回去整理!

原文地址:https://www.cnblogs.com/huaan011/p/6972540.html