ES6 Lesson #7 - Objects

In es6 simplifications appeared when working with objects and methods. Let's look at some examples.

First of all, you do not always need to declare the names in the object.

Example:

let hasYayca = "Chicken Eggs"
let hasBigMac = "Biggest Macs"
let hasValera = "Valera is Valera"


let yosip = {
   hasYayca,
   hasBigMac,
   hasValera
}

console.log(yosip)

// returns {hasYayca: "Chicken Eggs", hasBigMac: "Biggest Macs", hasValera: "Valera is Valera"}

Method example

Now you do not need to write the word function in the method completely, just write ()

let hasYayca = "Chicken Eggs"

let yosip = {
   hasYayca,
   sayValera() {
      console.log("Yosip has only eggs");
   }
}

console.log(yosip)

// returns {hasYayca: "Chicken Eggs"} "Yosip has only eggs"

But that is not all. Now you can create properties inside object dynamically. See an example below:

let itsValera = "Chicken Eggs"
let itsZags = "False Kingdom"


let yosip = {
   itsValera,
   itsZags 
}

let dynamicProp = "itsValera";

yosip = {
   [dynamicProp]: "Now its man egg not chicken"
}

console.log(yosip)
// returns { itsValera: "Now its man egg not chicken", itsZags:  "False Kingdom"}

For those who do not understand - in the example in the dynamicProp variable we specified the name of the property of the object, and passed it dynamically, without first creating it. One more example:

function callAdd(name, phone) {
  return {
    [name]: phone
  }
}

console.log(callAdd("troglodit", "+66699933666"))
// returns {troglodit: "+66699933666"}


In dynamic properties you can use functions on the fly.

function callAdd(name, phone) {
  return {
    ["_" + name.toUpperCase()]: phone
  }
}

console.log(callAdd("troglodit", "+66699933666"))
// returns {_TROGLODIT: "+66699933666"}

And we can use methods dynamically:

function callAdd(name, phone) {
  return {
    ['get' + name]() {
      return this[name];
    }
  }
}

console.log(callAdd("mehodnew", "+66699933666"))
// returns new method - {getmehodnew: ƒ}

Get and Set

The functions of receiving and changing the properties of object (get, set) do not need to be written separately, they can be written directly inside the object.

let ourValera = {
   name: "Valera",
   phone: "Valera has no phone",
   get valeraInfo() {
     return this.name + ' Bdusch ' + this.phone
   },
   set valeraPhone(value) {
     this.phone = value
   }
} 

ourValera.valeraPhone = "726261";
console.log(ourValera.valeraInfo) // returns Valera Bdusch 726261

console.log(ourValera)
// return {name: "Valera", phone: "726261"}