Enhanced object literals

In ES6, object literals support setting prototypes, shorthand assignments, defining methods, making super calls, and computing properties with expressions.

Let's see the following example, which creates an advisor object with a TeamMember object as its prototype:

1.  const advice = 'Stay hungry. Stay foolish.';
2.
3. let advisor = {
4. __proto__: new TeamMember('Adam', ['Consulting']),
5. advice,
6. greeting () {
7. super.greeting();
8. console.log(this.advice);
9. },
10. [advice.split('.')[0]]: 'Always learn more'
11. };

Line 4, assigning the object of TeamMember to the advisor object's __proto__ property makes advisor an instance of TeamMember:

console.log(TeamMember.prototype.isPrototypeOf(advisor));  // true
console.log(advisor instanceof TeamMember); // true

Line 5 is a shorthand assignment of advice:advice. Line 7 is creating the greeting() method of TeamMember, inside which it will invoke the greeting method of TeamMember:

advisor.greeting();   // I' m Adam. Welcome to the team!
// Stay hungry. Stay foolish.

In line 10, the Stay hungry property is calculated with bracket notation. And to access this property, in this case, because the property name contains a space, you need to use bracket notation, like this—advisor['Stay hungry'].

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.181.47