HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JavaScript - prototype, getters, setters, functions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
functionsjavascriptgettersprototypesetters

Problem

I'm just getting to know the whole prototype world, and now I'm trying to do in JS what is normally done in OO languages, namely classes and DAO classes.

I'd be grateful for any comments on whether the code is written in accordance to JS best practices and whatnot. More specifically, I didn't implement getters or setters per se, is my approach still sound?

function Person(obj) {
  this.id = obj.id;
  this.name = obj.name;
  this.surname = obj.surname;
}

Person.prototype.toString = function(){
  return "["+this.id+"] name: " + this.name + ", surname: " + this.surname;
};

/*
Field.prototype = {
    get value(){
        return this._value;
    },
    set value(val){
        this._value = val;
    }
};
*/

function PersonDAO(){
   this.arrayOfPeople = []; 
}

PersonDAO.prototype = {
  save:function(personObj){
    this.arrayOfPeople.push(personObj);
  },
  getAll:function(){
    return this.arrayOfPeople;
  }
};

var John = new Person({
  id: 1,
  name: "John",
  surname: "Smith"
});

var Bob = new Person({
  id: 2,
  name: "Bob",
  surname: "Doe"
});

var pDAO = new PersonDAO();
pDAO.save(John);
pDAO.save(Bob);
console.log(pDAO.getAll()[0].toString());

Solution

Though dynamic, you should not force JavaScript it to use complicated patterns that aren't worth the hassle. In your case, the code you want can be simplified into:

var people = [];

people.push({
  id: 1,
  name: "John",
  surname: "Smith"
});

people.push({
  id: 2,
  name: "Bob",
  surname: "Doe"
});


Another thing is that JavaScript has no natural concept of privacy (save closures of course). So when doing some prototypal OOP, almost everything is public. Getters and setters might not hold much purpose.

The key to a big JavaScript app is to never make it big in the first place. Keep components small, simple and easy to debug in case they go wild. Additional baggage will drag you down eventually.

Also, I suggest you don't modify native methods. Though it's common that developers do override some of them, like toString(). But some other code might use it in a way that it expects the native functionality. A general rule in JS is don't modify objects you don't own.

Code Snippets

var people = [];

people.push({
  id: 1,
  name: "John",
  surname: "Smith"
});

people.push({
  id: 2,
  name: "Bob",
  surname: "Doe"
});

Context

StackExchange Code Review Q#29343, answer score: 3

Revisions (0)

No revisions yet.