ES6学习--Object.assign()

ES6提供了Object.assign(),用于合并/复制对象的属性。

Object.assign(target, source_1, ..., source_n)

1. 初始化对象属性 

构造器正是为了初始化对象的属性,通常,我们不得不多次重复属性的名字。示例代码的constructor中,x与y均重复了两次:


class Point 

constructor(x, y) 

this.x = x; 
this.y = y; 

如果可以的话,个人偏爱将所有冗余都省去。(事实上,CoffeeScript与TypeScript都有语法解决构造器中属性名重复的问题。):


class Point 

constructor(this.x, this.y){} 

至少,Object.assign()可以帮助我们减少一些重复:


class Point 

constructor(x, y) 

Object.assign(this, { x, y }); 

var obj = new Point('a',1);
 obj; // {x:a,y:1}

 

在ES6中, { x, y }为{ x: x, y: y }的缩写。


2. 为对象添加方法 

ECMAScript 5, you use a function expression to add a method to an object:

 

在ES5中,需要使用function关键字定义对象的新增方法:


MyClass.prototype.foo = function(arg1, arg2) 

//... 
}; 

在ES6中,对象方法的定义更加简洁,不需要使用function关键字。这时,可以使用Object.assign()为对象新增方法:


Object.assign(MyClass.prototype, 

foo(arg1, arg2) 

//... 

}); 
3. 复制对象 

使用Object.assign()深度复制对象,包括其prototype


var Point = function(x) 

this.x = x; 

Point.prototype.y = 2; 
var obj = new Point(1); 
var copy = Object.assign({ __proto__: obj.__proto__ }, obj); // 输出{x:1,y:2} 
console.log(copy) // 输出{x:1,y:2} 
仅复制自身属性: 
var Point = function(x) 

this.x = x; 

Point.prototype.y = 2; 
var obj = new Point(1); 
var copy = Object.assign({}, obj); 
console.log(copy) // 输出{x:1} 

4)合并多个对象

将多个对象合并到某个对象。

const merge =
  (target, ...sources) => Object.assign(target, ...sources);

如果希望合并后返回一个新对象,可以改写上面函数,对一个空对象合并。

const merge =
  (...sources) => Object.assign({}, ...sources);

(5)为属性指定默认值

const DEFAULTS = {
logLevel:0,
outputFormat:'html'
};
function processContent(options){
options = Object.assign({},DEFAULTS,options);
console.log(options);
}
processContent();// {logLevel: 0, outputFormat: "html"}

上面代码中,DEFAULTS对象是默认值,options对象是用户提供的参数。Object.assign方法将DEFAULTS和options合并成一个新对象,如果两者有同名属性,则option的属性值会覆盖DEFAULTS的属性值

 

const DEFAULTS={
url:{
host:'example.com',
port:7070
},

};
function processContent(options){
options = Object.assign({},DEFAULTS,options);
console.log(options);
}
processContent({url:{port:8080}}); //{url: {port: 8080}}

 

 


参考 
Object properties in JavaScript 
Properties in JavaScript: definition versus assignment 
Callable entities in ECMAScript 6

posted @ 2018-12-05 15:54  如棋  阅读(176)  评论(0编辑  收藏  举报