`
zhouyrt
  • 浏览: 1128480 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

重写的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

 

 

分享到:
评论
1 楼 zhizhen23 2016-09-24  
LZ 提供的链接地址失效了

相关推荐

Global site tag (gtag.js) - Google Analytics