Search code examples
javascriptangularjsecmascript-5

Can I create a javascript function in EcmaScript 5 with the new get and set in one declaration?


I am very interested in ES5 getters and setters for use as Angular.js controllers. Currently I am doing:

var helloEC5 = function(){
  //constructor
  this.pants = "jeans";
};
helloEC5.prototype = {
    firstName: 'Seeya',
    lastName: 'Latir',
    get fullName() {
      console.log("get")
        return this.firstName + ' ' + this.lastName;
    },
    set fullName (name) {
      console.log('set')
        var words = name.toString().split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
}; 

But is there any way to do this in the function() succinctly together? What I really want is (pseudo code) ;

var helloEC5 = function() {
    firstName: 'Seeya',
    lastName: 'Latir',
    get fullName() {
      console.log("get")
        return this.firstName + ' ' + this.lastName;
    },
    set fullName (name) {
      console.log('set')
        var words = name.toString().split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
}; 

Solution

  • You can do it with the Object.defineProperty() method (http://jsfiddle.net/ydhLbwg6/):

    var helloEC5 = function () {
        this.firstName = 'Seeya';
        this.lastName = 'Latir';
        Object.defineProperty(this, 'fullName', {
            get: function () {
                console.log('get');
                return this.firstName + ' ' + this.lastName;
            },
            set: function (value) {
                console.log('set');
                var words = value.toString().split(' ');
                this.firstName = words[0] || '';
                this.lastName = words[1] || '';
            }
        });
    };