重写的isPlainObject方法

jq1.4中新增了个静态方法$.isPlainObject,见http://api.jquery.com/jquery.isPlainObject/ 。对于通过字面量定义的对象和new Object的对象返回true,new Object时传参数的返回false,如:

 

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,见: 关于 new Object 时传参的一些细节

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

 

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

 

感觉1.4新加的这个方法用处不大,只能判断由Object构造器生成的对象(传参数时例外),甚至一度以为这只是在jq内部用而已,但偏偏公开了,挂在了$上。当自定义一个类(构造器),用$.isPlainObject判断new自定义类的对象时将返回false。

 

//自定义类(构造器),创建一个对象p
function Person(){this.name='jack'}
var p = new Person();

$.isPlainObject(p); //-> false
 

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

 

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

测试:

 

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则不然。

修改下:

 

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

 

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

 

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

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

 

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

 

 

最后可以参考cai兄的讨论:http://cmc3.cn/n/2010/05/01/156.html

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值