object assign 用途

  • 为对象添加属性
  • 为对象添加方法
  • 浅克隆
  • 合并多个对象
  • 属性指定默认值
1
2
3
4
5
6
7
const DEFAULTS = {
logLevel: 0,
outputFormat: 'html'
};
function processContent(options) {
let options = Object.assign({}, DEFAULTS, options);
}

Object.create()、new Object()和{}的区别

直接字面量创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var objA = {};
objA.name = 'a';
objA.sayName = function() {
console.log(`My name is ${this.name} !`);
}
// var objA = {
// name: 'a',
// sayName: function() {
// console.log(`My name is ${this.name} !`);
// }
// }
objA.sayName();
console.log(objA.__proto__ === Object.prototype); // true
console.log(objA instanceof Object); // true

new关键字创建

1
2
3
4
5
6
7
8
9
var objB = new Object();
// var objB = Object();
objB.name = 'b';
objB.sayName = function() {
console.log(`My name is ${this.name} !`);
}
objB.sayName();
console.log(objB.__proto__ === Object.prototype); // true
console.log(objB instanceof Object); // true

Object.create 创建