Object.assign()メソッドでコンストラクタのプロパティを簡略化することができます。またオブジェクトを複製することが可能です。
コンストラクタのプロパティを簡略化
以下のようなBooksクラスがあります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Books { constructor(title, author, publisher) { this.title = title; this.author = author; this.publisher = publisher; } getTitle() { return this.title; } } let book1 = new Books('羅生門', '芥川龍之介', '新潮社'); console.log(book1.getTitle()); |
上記クラスのコンストラクタのプロパティをObject.assign()で簡略化しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Books { constructor(title, author, publisher) { Object.assign(this, { title, author, publisher }); } getTitle() { return this.title; } } let book1 = new Books('羅生門', '芥川龍之介', '新潮社'); console.log(book1.getTitle()); |
オブジェクトのマージ
Object.assign()を利用してオブジェクトをマージすることができます。
1 2 3 4 5 |
let title = { title: '羅生門' }; let author = { author: '芥川龍之介' }; let book = Object.assign(title, author); console.log(book); //{ title: '羅生門', author: '芥川龍之介' } |
重複するプロパティがある場合は、上書きされます。下記ではtitleが重複し上書きされています。
1 2 3 4 5 6 |
let book1 = { title: '羅生門', author: '芥川龍之介' }; let book2 = { title: '蜘蛛の糸', publisher: '新潮社' }; let book3 = Object.assign(book1, book2); console.log(book3); //{ title: '蜘蛛の糸', author: '芥川龍之介', publisher: '新潮社' } |
オブジェクトの複製
オブジェクトの複製の前に参照を説明します。下記のbook2はbook1の参照です。よってbook2のtitleを変更すると、book1のtitleも変更されてしまいます。
1 2 3 4 5 6 7 |
let book1 = { title: '羅生門', author: '芥川龍之介' }; let book2 = book1; book2.title = '蜘蛛の糸'; console.log(book1); //{ title: '蜘蛛の糸', author: '芥川龍之介' } console.log(book2); //{ title: '蜘蛛の糸', author: '芥川龍之介' } |
Object.assign()を利用すると、参照ではなく複製することが可能です。
1 2 3 4 5 6 7 |
let book1 = { title: '羅生門', author: '芥川龍之介' }; let book2 = Object.assign({}, book1); book2.title = '蜘蛛の糸'; console.log(book1); //{ title: '羅生門', author: '芥川龍之介' } console.log(book2); //{ title: '蜘蛛の糸', author: '芥川龍之介' } |
ただし下記のように、値としてオブジェクトがあるような階層が存在する場合、その部分は複製ではなく参照のままであることに注意して下さい。下記では4行目においてbook2の値を変更していますが、book1の値も変更されていることが確認できます。
1 2 3 4 5 6 7 8 |
let book1 = { title: '羅生門', author: '芥川龍之介', publisher: { a: '新潮社', b: '講談社' } }; let book2 = Object.assign({}, book1); book2.title = '蜘蛛の糸'; book2.publisher.a = '小学館'; console.log(book1); //{ title: '羅生門', author: '芥川龍之介', publisher: { a: '小学館', b: '講談社' } } console.log(book2); //{ title: '蜘蛛の糸', author: '芥川龍之介', publisher: { a: '小学館', b: '講談社' } } |
その場合は、別の方法で複製します。
1 2 3 4 5 6 7 8 |
let book1 = { title: '羅生門', author: '芥川龍之介', publisher: { a: '新潮社', b: '講談社' } }; let book2 = JSON.parse(JSON.stringify(book1)); book2.title = '蜘蛛の糸'; book2.publisher.a = '小学館'; console.log(book1); //{ title: '羅生門', author: '芥川龍之介', publisher: { a: '新潮社', b: '講談社' } } console.log(book2); //{ title: '蜘蛛の糸', author: '芥川龍之介', publisher: { a: '小学館', b: '講談社' } } |
参照ページ