Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Alexis374 opened this issue Feb 9, 2016 · 1 comment
Open

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

Alexis374 opened this issue Feb 9, 2016 · 1 comment

Comments

@Alexis374
Copy link
Owner

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

@Alexis374 Alexis374 modified the milestones: comments, blog context Feb 9, 2016
@BuptStEve
Copy link

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

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

  F.prototype = o;

  return new F();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants