Object.assign
constructor functionを定義するとき
code:js
const sandraKayeProfileData = {
name: 'Sandra Kaye',
portfolio: 'www.sandrasportfolio.com',
currentJob: 'Google',
currentSalary: '400k'
}
const DevProfile(data) {
this.name = data.name
this.portfolio = data.portfolio
this.currentJob = data.currentJob
currentSalary = data.currentSalary
}
const sandraKaye = new DevProfile(sandraKayeProfileData)
のようにも初期化できるが、いちいちthis.nameなどすべて書くのが面倒。そんなときにObject.assign()が使える。
code:js
const sandraKayeProfileData = {
name: 'Sandra Kaye',
portfolio: 'www.sandrasportfolio.com',
currentJob: 'Google',
currentSalary: '400k'
}
function DevProfile(data){
Object.assign(this, data) // here
this.summariseDev = function(){
console.log(${this.name}'s porfolio is at ${this.portfolio} and they work at ${this.currentJob}. Their current salary is ${this.currentSalary}.)
}
}
const sandraKaye = new DevProfile(sandraKayeProfileData)
sandraKaye.summariseDev()
Object.assign(target, object)と覚える。
code:js
const sandraKayeProfileData = {
name: 'Sandra Kaye',
portfolio: 'www.sandrasportfolio.com',
currentJob: 'Google',
currentSalary: '400k'
}
const target = {}
Object.assign(target, sandraKayeProfileData)