Object() 构造函数
该Object构造函数会为给定值的对象包装程序。
在非构造函数上下文中调用时,Object其行为与 new Object().
let o = new Object(undefined)
let o = new Object(null)
静态方法
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.
从源对象中复制所有可枚举属性到目标对象,返回重定义的源对象
let p1= {name:'gromy'}
let p2 = {name:'lucy',age:18}
let result = Object.assign(p2,p1)
p1
{name: 'gromy'}
p2
{name: 'gromy', age: 18}
result
{name: 'gromy', age: 18}
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),并返回这个新对象
const person = {
isHuman: false,
printIntroduction: function() {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};
const me = Object.create(person);
me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten
me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"
相当于
let me = {}
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)
语法
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.