timpal0l
timpal0l

Reputation: 63

Getters and Setters in JavaScript (Correct syntax ?)

I am new to JavaScript, but not to OOP in general.

Is this a valid way of creating getters & setters in JavaScript?

The "class",

function Person (age){
    this.age = age;
};

Getter,

Person.prototype.getAge = function(){
    return this.age;
};

and a setter.

Person.prototype.setAge = function(arg){
    this.age = arg;
};

It seems to work fine, but I dont know the convention, I get diffrent descriptions everywhere, but is my solution valid?

Upvotes: 3

Views: 102

Answers (1)

csuwldcat
csuwldcat

Reputation: 8249

You probably want Object.defineProperty (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty), here's an example of it in use:

Object.defineProperty(Person.prototype, 'age', {
  get: function(){
    return this.__age__;
  },
  set: function(value){
    this.__age__ = value;
  }
});

You can also hold a variable somewhere else if you want. The following would act as a singleton value that is set and accessed across all instances of Person:

var age;

Object.defineProperty(Person.prototype, 'age', {
  get: function(){
    return age;
  },
  set: function(value){
    age = value;
  }
});

If you want an age variable for every instance of the Person objects you create, you need to add the variable declaration inside your constructor:

function Person(){
  var age; 
  // ditto from the second example
}

Upvotes: 2

Related Questions