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

【JS】new和Object.create的区别 #76

Open
Easay opened this issue May 8, 2021 · 0 comments
Open

【JS】new和Object.create的区别 #76

Easay opened this issue May 8, 2021 · 0 comments
Labels

Comments

@Easay
Copy link
Owner

Easay commented May 8, 2021

  • Object.create

该方法接收两个参数:obj和propertiesObject;

obj:新创建的对象的原型
propertiesObject:可选,该参数对象是一组属性与值

var o = Object.create(Object.prototype, {
  // foo会成为所创建对象的数据属性
  foo: { 
    writable:true,
    configurable:true,
    value: "hello" 
  },
  // bar会成为所创建对象的访问器属性
  bar: {
    configurable: false,
    get: function() { return 10 },
    set: function(value) {
      console.log("Setting `o.bar` to", value);
    }
  }
});

Object.create(null)和new Object()的区别:
两者都是创建空对象,但是new创建出的空对象会绑定Object的prototype原型对象,但是Object.create(null)的空对象是没有任何属性的。

总结

new操作符会将构造函数的prototype指定的原型对象赋值给新对象的[[Prototype]]
Object.create将参数proto指定的原型对象赋值给新对象的[[Prototype]]
如果参数为null的话,Object.create则会创建空对象。

@Easay Easay added the JS label May 8, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant