官术网_书友最值得收藏!

  • JavaScript:Moving to ES2015
  • Ved Antani Simon Timms Narayan Prusty
  • 592字
  • 2021-07-09 19:07:36

Getters and setters

Getters are convenient methods to get the value of specific properties; as the name suggests, setters are methods that set the value of a property. Often, you may want to derive a value based on some other values. Traditionally, getters and setters used to be functions such as the following:

var person = {
  firstname: "Albert",
  lastname: "Einstein",
  setLastName: function(_lastname){
    this.lastname= _lastname;
  },
  setFirstName: function (_firstname){
    this.firstname= _firstname;
  },
  getFullName: function (){
    return this.firstname + ' '+ this.lastname;
  }  
};
person.setLastName('Newton');
person.setFirstName('Issac');
console.log(person.getFullName());

As you can see, setLastName(), setFirstName(), and getFullName() are functions used to do get and set of properties. Fullname is a derived property by concatenating the firstname and lastname properties. This is a very common use case and ECMAScript 5 now provides you with a default syntax for getters and setters.

The following example shows you how getters and setters are created using the object literal syntax in ECMAScript 5:

var person = {
  firstname: "Albert",
  lastname: "Einstein",
  get fullname() {
    return this.firstname +" "+this.lastname;
  },
  set fullname(_name){
    var words = _name.toString().split(' ');
    this.firstname = words[0];
    this.lastname = words[1];
  }
};
person.fullname = "Issac Newton";
console.log(person.firstname); //"Issac"
console.log(person.lastname);  //"Newton"
console.log(person.fullname);  //"Issac Newton"

Another way of declaring getters and setters is using the Object.defineProperty() method:

var person = {
  firstname: "Albert",
  lastname: "Einstein",
};
Object.defineProperty(person, 'fullname', {
  get: function() {
    return this.firstname + ' ' + this.lastname;
  },
  set: function(name) {
    var words = name.split(' ');
    this.firstname = words[0];
    this.lastname = words[1];
  }
});
person.fullname = "Issac Newton";
console.log(person.firstname); //"Issac"
console.log(person.lastname);  //"Newton"
console.log(person.fullname);  //"Issac Newton"

In this method, you can call Object.defineProperty() even after the object is created.

Now that you have tasted the object-oriented flavor of JavaScript, we will go through a bunch of very useful utility methods provided by Underscore.js. We discussed the installation and basic usage of Underscore.js in the previous chapter. These methods will make common operations on objects very easy:

  • keys(): This method retrieves the names of an object's own enumerable properties. Note that this function does not traverse up the prototype chain:
    var _ = require('underscore');
    var testobj = {
      name: 'Albert',
      age : 90,
      profession: 'Physicist'
    };
    console.log(_.keys(testobj));
    //[ 'name', 'age', 'profession' ]
  • allKeys(): This method retrieves the names of an object's own and inherited properties:
    var _ = require('underscore');
    function Scientist() {
      this.name = 'Albert';
    }
    Scientist.prototype.married = true;
    aScientist = new Scientist();
    console.log(_.keys(aScientist)); //[ 'name' ]
    console.log(_.allKeys(aScientist));//[ 'name', 'married' ]
    
  • values(): This method retrieves the values of an object's own properties:
    var _ = require('underscore');
    function Scientist() {
      this.name = 'Albert';
    }
    Scientist.prototype.married = true;
    aScientist = new Scientist();
    console.log(_.values(aScientist)); //[ 'Albert' ]
  • mapObject(): This method transforms the value of each property in the object:
    var _ = require('underscore');
    function Scientist() {
      this.name = 'Albert';
      this.age = 90;
    }
    aScientist = new Scientist();
    var lst = _.mapObject(aScientist, function(val,key){
      if(key==="age"){
        return val + 10;
      } else {
        return val;
      }
    });
    console.log(lst); //{ name: 'Albert', age: 100 }
  • functions(): This returns a sorted list of the names of every method in an object—the name of every function property of the object.
  • pick(): This function returns a copy of the object, filtered to just the values of the keys provided:
    var _ = require('underscore');
    var testobj = {
      name: 'Albert',
      age : 90,
      profession: 'Physicist'
    };
    console.log(_.pick(testobj, 'name','age')); //{ name: 'Albert', age: 90 }
    console.log(_.pick(testobj, function(val,key,object){
      return _.isNumber(val);
    })); //{ age: 90 }
  • omit(): This function is an invert of pick()—it returns a copy of the object, filtered to omit the values for the specified keys.
主站蜘蛛池模板: 公主岭市| 沙洋县| 墨脱县| 河池市| 新巴尔虎右旗| 文安县| 灯塔市| 新兴县| 大姚县| 普格县| 宜章县| 株洲县| 凌源市| 黄平县| 确山县| 金昌市| 嵩明县| 奉化市| 景宁| 仪陇县| 即墨市| 绵竹市| 公安县| 唐山市| 永城市| 永胜县| 莆田市| 拜城县| 上杭县| 曲阳县| 保山市| 繁峙县| 铅山县| 蓬安县| 吉木乃县| 八宿县| 湄潭县| 甘德县| 塔河县| 新建县| 抚松县|