重写的isPlainObject方法

jq1.4中新增了个静态方法$.isPlainObject,见http://api.jquery.com/jquery.isPlainObject/

对于通过字面量定义的对象和new Object的对象返回true,new Object时传参数的返回false,如

1
2
3
4
5
6
7
var p1 = new Object;
p1.name = 'tom';
var o1 = new Object('aa');
console.log($.isPlainObject({name:'Jack'})); //-> true
console.log($.isPlainObject(p1));        //-> true
console.log($.isPlainObject('aa'));      //-> false
console.log($.isPlainObject(o1));        //-> false 

$.isPlainObject(o1)返回也是false。

通过字面量定义的对象,其构造器是Object,很容易证明。

1
2
var obj = {};
console.log(obj.constructor === Object); //-> true

jq1.4新加的这个方法用处不大,只能判断由Object构造器生成的对象(传参数时例外),甚至一度以为这只是在jq内部用而已,但偏偏公开了,挂在了$上。

当自定义一个类(构造器),用$.isPlainObject判断new自定义类的对象时将返回false。

1
2
3
4
5
//自定义类(构造器),创建一个对象p
function Person(){this.name='jack'}
var p = new Person();
 
$.isPlainObject(p); //-> false

因此想写一个对于通过字面量定义及通过自定义类(构造器)创建的对象都返回true的方法。

1
2
3
function myIsPlainObject( obj ){
    return Object.prototype.toString.call(obj)==='[object Object]';
}

测试下

1
2
3
4
5
6
7
8
function Person(name){
    this.name=name;
}
var p = new Person('jack');
var o = {name:'tom'};
 
console.log(myIsPlainObject(p)); //-> true
console.log(myIsPlainObject(o)); //-> true

都返回true,一切貌似很顺利。

偏偏IE中window/document/document.body/HTMLElement/HTMLCollection/NodeList/也返回true。
即IE中Object.prototype.toString.call以上对象返回的字符串也是'[object Object]',不知IE为何这样实现,Firefox/Chrome/Safari/Opera则不然。修改下

1
2
3
function myIsPlainObject( obj ){
    return 'isPrototypeOf' in obj && Object.prototype.toString.call(obj)==='[object Object]';
}

这里判断obj是否具有isPrototypeOf属性,isPrototypeOf是挂在Object.prototype上的。通过字面量或自定义类(构造器)创建的对象都会继承该属性方法,在有约定的情况下,这个方法可以使用。

1
2
console.log(myIsPlainObject(window));   //-> false
console.log(myIsPlainObject(document)); //-> false

但不遵守约定的情况下,仍然失败,如在window上人为的 添加isPrototypeOf属性

1
2
window.isPrototypeOf = '';
console.log(myIsPlainObject(window)); //-> true

相关:

关于 new Object 时传参的一些细节 

isPlainObject 判断是否为字面量对象 

posted on   snandy  阅读(3063)  评论(3编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
< 2011年3月 >
27 28 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9

统计

点击右上角即可分享
微信分享提示