Saturday, March 10, 2012

JavaScript OOP - Extending Objects

An interesting concept in Objective-C is the Category. Categories allow developers to add methods to existing Classes, even if the source code is unavailable. This can be done in JavaScript by adding functions to an existing class' prototype. This article demonstrates how to add methods to Array.

/*
  * Function: removeItem
  *  This function removes all occurrences of this item
  *  
  * Parameter:
  *  item - The item being removed. Can be primitive or object. If object must be same instance.
  */
 Array.prototype.removeItem = function(item){
  var length = this.length, i;
  
  for(i=0; i < length; i++){
   var member = this.pop();
   
   if(member !== item){
    this.unshift(member);
   }
  }
 };
Now items can be removed from any array just by calling that method.
//Remove Numbers
var numberArr = [1,2,3,2];
console.log(numberArr); // 1 2 3 2
numberArr.removeItem(2);
console.log(numberArr); // 1 3

//Remove string
var numberArr = ["1","2","3","2"];
console.log(numberArr); // "1" "2" "3" "2"
numberArr.removeItem("2");
console.log(numberArr); // "1" "3"

How cool is that? Even objects defined with native code can be extended to increase their utility and ease of use.

No comments:

Post a Comment