Open
Description
Object.create(nulll)
和 {}
一样么?
在翻看qs模块的源码的时候,看到其utils.js中有:
exports.arrayToObject = function (source, options) {
var obj = options.plainObjects ? Object.create(null) : {};
for (var i = 0, il = source.length; i < il; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
看到函数体内第一行,才发现两者竟然不一样。经过google发现有人已经问过.
两者区别如下:{}
指定其原型为Object.prototype
会从Object.prototype
继承toString
之类的方法,在chrome控制台下声明a={}
,然后打出a.,浏览器会自动补全;而Object.create(null)
则不指定原型,在控制台下输入b=Object.create(null)
然后输入b. 不会自动补全。
所以 {}
是Object.create(Object.prototype)
等价的。