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

I'm very interested in ES5 receivers and setters for use as Angular.js controllers. I am currently 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 a way to do this in function () concisely together? I really want (pseudocode);

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] || '';
    }
}; 

      

+3


source to share


1 answer


You can do it with 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] || '';
        }
    });
};

      

+5


source







All Articles