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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值