4

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] || '';
    }
}; 
httpete
  • 2,765
  • 26
  • 34
  • possible duplicate of [Getter/setter in constructor](http://stackoverflow.com/questions/5222209/getter-setter-in-constructor) – cookie monster Sep 21 '14 at 22:02

1 Answers1

6

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] || '';
        }
    });
};
Korikulum
  • 2,529
  • 21
  • 25
  • Too wordy for me, I wonder if https://github.com/Baqend/jahcode is a good compromise between brevity and native goodness? – httpete Sep 21 '14 at 23:36
  • Where is the constructor on that? Is there any standard way to mixin constructor arguments as properties? – httpete Sep 22 '14 at 01:52