OO Javascript

other languages: Italian

This document contains some hints on how to use for object oriented programming.

jQuery snippets

Some snippets of code showing how to use jQuery

// return true if the element is an input
$('#elementId').is('input');
// get the name of the tag
$('#elementId').get(0).tagName

Plain Object Definition

simple example: define an object in javascript [link_01]

This sample show how to define and use an object in javascript.
First the object is created, like a function; then we add a constructor and a method using the prototype property.

// define Object as a function
function StringBuffer(){
  this.buffer = [];
}
// add a constructor with one string parameter
StringBuffer.prototype.append = function append(string){
  this.buffer.push(string);
  return this;
}
// add one method to the object
StringBuffer.prototype.toString = function toString(){
  return this.buffer.join('');
}

Now we can instantiate the object and use its data and methods.

// new instance
var buf = new StringBuffer();
// use the instance
buf.append('hello');
buf.append('world');
alert(buf.toString());

References