Alexis374 / tech_post

record the technique and thinking when I am coding and learning

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Object.create(nulll) 和 {} 一样么?

Alexis374 opened this issue · comments

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)等价的。

是哒~记得高程里写过,当 Object.create() 只传一个参数时,和以下方法行为相同。

function object(o) {
  function F() {}

  F.prototype = o;

  return new F();
}