Skip navigation

Tag Archives: object oriented javascript


Everything in javascript is object. It a powerful feature. So Array is object. Stay focused.

// straight forward object, property creation & storing, retrieving value 
var obj = {}; // equivalent of new Object()
obj.age = 22; // create a property age and store value in it
console.log(obj.age); // 22
console.log(obj['age']); // 22
//

Now comes the interesting part with array. Still remembering Array is an object??

//
var arr = [];  // equivalent of new Array()
arr[0] = 'one';  // adds to the array
arr[1] = 'two';  // adds to the array
arr['age'] = 22; // does not add to the array but with property above
console.log(arr.length);  // 2 not 3
// gotcha
for(me in arr) {
  // still you will get 'age' here  !!!!
}
//

Hold on, we are going to explore Array like objects now. Array like objects have length property, numbered elements. Yes, it stops there. It does not have push(), pop(), sort(), splice(), etc. ie. any of Array functions. You can’t even loop through it. Perfect example for these kind of objects are HTML node sets like document.forms, document.getElementByTagName(), etc. Even arguments object also belongs to this category. Now let us jump into code to prove these points.

//
console.log(document.forms.length);  // 1 if you have one form element
document.forms[0]; // return first form in the document
document.forms.join(', '); // throws error !!!
// another example
function arrayLike(a,b) {
  alert(arguments.length);  // No error. works fine. arguments is a property created automatically with every function
  for(var i=0;i<arguments.length;i++) {
    alert("parameters "+ i + " is " + arguments[i]);  // works fine
  }
  alert("your parameters were " + arguments.join(", "));  // throws error
}
//

Now comes interesting part. How to convert array like object to get benefits of array functions??

//
function behave(a,b){
  var para = Array.prototype.slice.call(arguments);  // this needs explanation. read below
  alert(" arguments " + para.join(", "));   // works fine
}
//

Read note in the specification document.

Array: original object from where all array inherit their functions like join, pop, etc.
Array.prototype: this gives access to all functions in Array object
Array.prototype.slice: the native method; take this as Array but not arguments
Array.prototype.slice.call: call is prototype methods of Function which available to all functions; call changes the this context to the first argument passed

Wow!! Finally slice will return array object though whatever we pass in.

Bit lengthy post this time. Feel free to shoot your questions in the comment section.

Another proof.


this is powerful but at the same time if used without care it is dangerous too. Consider the example snippet below

// define Human class
var Human = function(name) {
    this.name = name;
    this.say = function(){
        return "I am " + this.name;
    };
};
var author = new Human('raja');
var badAuthor = Human('ford');  // new keyword missing

alert(typeof author); // object
alert(typeof badAuthor); // undefined because context changed to window
alert(author.name)  // raja
alert(window.name)  // ford

Notice how missing new keyword changing the context to window object.

Play with it.


Definition for closure : A closure is the local variables for a function – kept alive after the function has returned.

A nice example to explain closure.

//
// define a function which preserves data (count)
//
var CreateCounter = function(){
   var count, f;
   count = 0;
   f = function(){
      count = count+1;
      return count;
   }
   return f;
}

// create objects which remembers its own counter
var counter1 = CreateCounter();
var counter2 = CreateCounter();
alert(counter1());  // 1
alert(counter1());  // 2
alert(counter1());  // 3

alert(counter2());  // 1
alert(counter2());  // 2
alert(counter2());  // 3

alert(counter1());  // 4
alert(counter1());  // 5
alert(counter2());  // 4

Nice article about closure found at http://www.jibbering.com/faq/faq_notes/closures.html

Follow

Get every new post delivered to your Inbox.

Join 150 other followers