3

I am building a javascript library where I have to create a log of classes and most of them have a lot of properties which have to make public for the user.

For example:

function Person(name,age){

}

Now I want to create the getter and setter for properties (name and age).

Nornall, I have to add these methods to Person.prototype:

Person.prototype.getName=function(){}
Person.prototype.setName=function(x){
  //check if x is typeof String
}
Person.prototype.getAge=function(){}
Person.prototype.setAge=function(x){
  //check if x is typeof Number
}

This will result in two many lines of repeated codes.

So I wonder if I can call a method like this:

makeThesePropertiesPublic(Person,{
  name:"string",
  age:"number"
});

Then I can call this:

var p=new Person("xx",1);
p.getName();
p.getAge();
.......

Is there a out-of-box method to implement this?

hguser
  • 35,079
  • 54
  • 159
  • 293
  • see if this helps: http://stackoverflow.com/questions/812961/javascript-getters-and-setters-for-dummies – Mortalus Jul 04 '13 at 02:45

2 Answers2

3

First of all you can't define the getter and setter functions on the prototype because they need to be able to access name and age which are only accessible inside the constructor. Hence you would need to define the getter and setter functions inside the constructor.

I would do this:

function Person(name, age) {
    var private = {
        name: name,
        age: age
    };

    Object.defineProperties(this, {
        name: getAccessor(private, "name", "String"),
        age: getAccessor(private, "age", "Number")
    });
}

function getAccessor(obj, key, type) {
    return {
        enumerable: true,
        configurable: true,
        get: function () {
            return obj[key];
        },
        set: function (value) {
            if (typeOf(value) === type)
                obj[key] = value;
        }
    };
}

function typeOf(value) {
    return Object.prototype.toString.call(value).slice(8, -1);
}

Now you can access create a Person and access their name and age properties as follows:

var person = new Person("Aadit M Shah", 20);

person.name = 0;       // it won't set the name
person.age = "twenty"; // it won't set the age

alert(person.name);
alert(person.age);

See the demo: http://jsfiddle.net/aVM2J/

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
0

What about something like this?

function Person(n, a) {

    var name = n;
    var age = a;

    var person = {};
    person.getName = function () {
         return name
    }

    person.getAge = function () {
         return age;
    }


    return person;
}
var p = Person("jon",22);
console.log(p.getName());//jon
HMR
  • 37,593
  • 24
  • 91
  • 160
sma
  • 9,449
  • 8
  • 51
  • 80