Object() 构造函数

Object构造函数会为给定值的对象包装程序。

  • 如果值为nullor undefined,它将创建并返回一个空对象。
  • 否则,它将返回与给定值对应的类型的对象。
  • 如果该值已经是一个对象,它将返回该值。

在非构造函数上下文中调用时,Object其行为与 new Object().

  1. let o = new Object(undefined)
  2. let o = new Object(null)

image.png

静态方法

Object.assign(source,target)

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
从源对象中复制所有可枚举属性到目标对象,返回重定义的源对象

  1. let p1= {name:'gromy'}
  2. let p2 = {name:'lucy',age:18}
  3. let result = Object.assign(p2,p1)
  4. p1
  5. {name: 'gromy'}
  6. p2
  7. {name: 'gromy', age: 18}
  8. result
  9. {name: 'gromy', age: 18}
  10. result === p2 //目标对象

结论

源对象中和目标对象相同的属性会被 目标对象覆盖。

Object.create()

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
Object.create() 使用一个已存在的对象的原型 作为 新对象的原型(proto),并返回这个新对象

  1. const person = {
  2. isHuman: false,
  3. printIntroduction: function() {
  4. console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  5. }
  6. };
  7. const me = Object.create(person);
  8. me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
  9. me.isHuman = true; // inherited properties can be overwritten
  10. me.printIntroduction();
  11. // expected output: "My name is Matthew. Am I human? true"

相当于

  1. let me = {}
  2. me.__proto__ = person.__proto__

Object.defineProperty()

The static method Object.defineProperty() defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
Object.defineProperty() 可以直接定义或者修改 对象上的属性,并返回这个对象

By default, values added using Object.defineProperty() are immutable and not enumerable.
默认情况下,使用 Object.defineProperty() 添加的属性是不可变且 不可枚举的 (for..in)

语法

  1. Object.defineProperty(obj, prop, descriptor)

obj:The object on which to define the property.
prop:The name or Symbol of the property to be defined or modified.
descriptor:The descriptor for the property being defined or modified.