Friday, October 25, 2019

[JS][Example] JavaScript ES6 feature : Enhanced Object Literals

Example 1
ECMAScript 6 :
function Person(name,age,gender){
  return {
    name,
    age:age,
    gender,
    ["is"+gender]:true,
    makeSelfIntro(){
      return `I am ${name} and is ${age} years old, is a ${gender}. `
    }
  }
}
let people = [Person("Sam",45,"male"),
              Person("Ann",15,"female")];
document.write(people[0].makeSelfIntro());
Result is I am Sam and is 45 years old, is a male.

script write by ECMAScript 2015:
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function Person(name, age, gender) {
  var _ref;
  return _ref = {
    name: name,
    age: age,
    gender: gender
  }, _defineProperty(_ref, "is" + gender, true), _defineProperty(_ref, "makeSelfIntro", function makeSelfIntro() {
    return "I am ".concat(name, " and is ").concat(age, " years old, is a ").concat(gender, ". ");
  }), _ref;
}
var people = [Person("Sam", 45, "male"), Person("Ann", 15, "female")];
document.write(people[0].makeSelfIntro());
Reference:
https://dev.to/sarah_chima/enhanced-object-literals-in-es6-a9d

No comments :

Post a Comment