Object.assign() IE不支持
将所有可枚举属性的值从一个或多个源对象复制到目标对象
const object1 = {
a: 1,
b: 2,
c: 3
};
const object2 = Object.assign({c: 4, d: 5}, object1);
console.log(object2.c, object2.d);
// expected output: 3 5
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"是"me"的属性, "person"没有这个属性
me.isHuman = true; // 继承属性可以被重写
Object.defineProperty() IE9+
添加或修改对象上的属性
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
object1.property1 = 77;
// throws an error in strict mode
console.log(object1.property1);
// expected output: 42
Object.defineProperties() IE9+
同时添加多个属性
Object.hasOwnProperty()
返回布尔值,说明对象中是否含有这个属性
o = new Object();
o.hasOwnProperty('prop'); // returns false
o.prop = 'exists';
o.hasOwnProperty('prop'); // returns true
