Nothing Insightful

  • Archive
  • RSS

JavaScript Prototype “Class” Manager

I thought I’d share an amazing little snippet of code I picked up months ago, and that I haven’t been able to find anywhere else since. My latest Workflow project I’ve been blogging about forced me to finally teach myself OO JavaScript. It’s been stressful, but rewarding.

Creating object oriented code was pretty cool, but storing each object in an array (and subsequently performing functions on this array) is a completely different matter. After some chatting on the #javascript channel on freenode, someone gave me this absolute nugget:

/* === MANAGER CLASS === */

var Manager = function(cons) {

  this.cons = cons;

  this.objs = [];

};

Manager.prototype.create = function(args) {

  var inst = new this.cons(args)

  this.objs.push(inst);

  return inst;

};

Manager.prototype.all = function() {

  return this.objs;

};

Manager.prototype.findBy = function(p, v) {

  for(var i = 0, len = this.objs.length; i < len; i++) { 

if(this.objs[i][p] === v) {

 return this.objs[i];

}

  }

};

Manager.prototype.remove = function(o) {

for(var i = 0, len = this.objs.length; i < len; i++) {

if(this.objs[i].id === o.id) {

this.objs.splice(i,1);

i = this.objs.length;

}

}

};

If you have an object you’ve created, such as the following:

var Person = function() {
    this.init();
}

It just becomes a matter of creating a new instance of the manager “class” and specifying the constructor:

var AddressBook = new Manager(Person);

AddressBook.create({FirstName: “Bob”});

While plenty of critics are going to rush to the comments section describing what are and are not “classes” (and that it’s not possible to have true classes in JavaScript) this is a great starting point. I’ve reused this code in many locations, and given it to others in my workplace. I hope it serves you well.

    • #javascript
    • #oop
    • #snippet
  • 2 years ago
  • 8
  • Comments
  • Permalink
  • Share

8 Notes/ Hide

  1. psdtohtmlshop reblogged this from taitems
  2. vieciterca likes this
  3. jotarun likes this
  4. taitems posted this

Recent comments

Blog comments powered by Disqus
← Previous • Next →

About

My name is Tait Brown, and I'm a Melbourne-based UI designer and a front end developer. I like to make stuff.

taitbrown.com

taitbrown@gmail.com

Me, Elsewhere

  • taitems on Dribbble
  • taitems on Forrst
  • @taitems on Twitter
  • taita_cakes on Last.fm
  • Linkedin Profile
  • taitems on github

Twitter

loading tweets…

  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr