Garmon's Javascript #1 - Simple Object Database - Learn basic Object-Oriented Programming

free web hosting
Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > Client Side Scripting > Javascript

Garmon's Javascript #1 - Simple Object Database - Learn basic Object-Oriented Programming

Garmon Sutrix
Okay, so you're like me - you've heard about OOP or Object Oriented Programming and wonder what all the hOOPlah is about! So here's the straight pOOP. Okay, sorry for the stOOPid puns. I'll stop now. Honestly, I will. OOPs I did it again.

Right.

Here's the scenario: we have an online store, we want to maintain a database of our products, and we want to be able to access them. This tutorial shows how this can be done, with very simple, commented code.

Please note, that I'm not recommending that you use JavaScript to store your actual product data. For one thing, client-side JavaScript is not persistent, so your product information will disappear as soon as the browser window's closed. Your actual information would be stored in a database somewhere (like a mySQL database) which you could access via Perl or some other scripting language.

What you WOULD use JavaScript for is your presentation layer. So for example, you want people to be able to see a quick display of the products, with an image, a description etc. And maybe they should be able to quickly switch between products, perhaps using a pull-down menu. Whatever. The point of this example is to learn some object-oriented basics, not to create the next OSCommerce.



The following code shows how easy it is to create objects using JavaScript. In this example, we are dealing with two custom objects: a ProductDatabase object which would be a local mirrored copy of some (or all) of your actual product database which as mentioned above would be in mySQL or Oracle; and a Product object, which would describe one single product item.

The ProductDatabase object will then contain all your Product objects. And it will also provide tools (in OOP-speak "methods") by which you can create and manipulate those product objects. To access your individual product objects (by name), just call the ProductDatabase.getProdByName() method.

I'm not an OOP expert, so I won't lecture you on complex object-oriented programming concepts such as inheritance and prototypes. This is just the basics, folks, from someone who wants some free webhosting. However, there are just a couple of things I would like to point out about objects:

1. an object is created using a "constructor" function. Basically this is a function you define at the highest level of your code that gest used to create an instance of the object whenever it is called, and populate that object with whatever starting values you want. It's really easy. Define your object constructor like a function:
CODE
function MyObject() {
  // this is the constructor function for the MyObject object

  //purists like me like to return the object, but it's not necessary
  return (this);
}


You then create an instance of that object like this:
CODE
var myNewObj1 = new MyObject();


Often, you want to give information to the object when you are creating it. You can do this with parameters, just like you would with any other function. Pass parameters to a new object like this:
CODE
var myNewObj2 = new MyObject("Hello World!!");


And receive the parameters in the object constructor like this:
CODE
function MyObject(myParameter1){
   alert (myParameter1);
}


2. an object instance should be assigned to a variable, or at least stored anonymously somewhere so that you don't lose it. You can do that very simply by assigning the object to a variable like this:
var myProdObject = new Product().

Or you can put the object anonymously into an array right away like this:
my productArray[0] = new Product().

You can then get at that object later like this:
productArray[0].

3. an object can have properties associated with it. These are your attributes. In the case of the Product object below, these would be things like price, product name, product description etc... The properties get stored with the object. You can do that easily (within the object constructor) like this:
this.propertyName = value.

Here's an example:
CODE
function MyObject(){
   this.colour = "blue";
   this.itemType = "widget";
}


Later, you can access these properties like this:
CODE
var myNewObj3 = new MyObject();
alert (myNewObj3.colour);


But you can see here that if I create another object instance using the same constructor, it will also have the same values. Look to point #2 above to see what the solution is: use parameters when you create the object and assign those values to the object's properties, like this:
CODE
function MyObject(userColour, userType){
   this.colour = userColour;
   this.itemType = userType;
}


And create a couple of instances like this:
CODE
var myNewObj4 = new MyObject("blue", "widget");
var myNewObj5 = new MyObject("green", "grommet");


So as long as you don't lose the object (ie: destroy the variable that contains that instance of the object), all its properties get "carried along" with it. You can access them later using regular "dot syntax" as in:
alert (myNewObj5.colour)

or (for the Products object in the long listing below)
alert(myProductObject.prodName).

or as per the array example above:
productArray[0].prodName.

4. an object can have methods associated with it. Basically, methods are functions that are attached to the object. Only objects that are instances of that object type would have access to that method. The method works primarily with the properties of that object (see #3 above), but can access external methods and properties, though I hear that purists frown on this sort of behaviour. OOPs!

Attach a method (function) to an object like this:
this.methodName = function() { // function goes here }

Within the function, access the properties of the object using the "this" dot notation. Here's a simple example from previous snippets:
CODE
function MyObject (userColour){
   this.colour = userColour;

   // here's a method
   this.showColourAlert = function() {
       alert (this.colour);
   }
}

// let's put that new method to use in a new instance of the object:
var myNewObj6 = new MyObject("puce");
myNewObj6.showColourAlert();



There you go, the basics. I'm pretty much at the limit of my object-oriented know-how anyway, so best I quit with an example that puts it all together.

CODE
// this function creates a prodDatabase object and populates it with a few Product objects and then accesses one of the product items by name
         function example(){
              // create a few new product objects and add them to the product list
              prodDatabase = new ProductDB();
             
              prodDatabase.addProduct (1102, 10.99, "Widget 1", "This is a widget.", "image1.jpg");
              prodDatabase.addProduct (1143, 22.98, "Rotor", "This is a fanbelt rotor assembly.", "rotor1.jpg");
             
              alert (prodDatabase.getProdByIndex(0).price);
              alert (prodDatabase.getProdByName("Rotor").prodDesc);
         }
         
         
         // the Product DB constructor
         function ProductDB(){
              this.productArray = new Array(); // for storing the list of products
             
              // this method creates a new product object and adds it to the database
              this.addProduct = function (prodID, price, prodName, desc, prodImage){
                   this.productArray.push (new Product (prodID, price, prodName, desc, prodImage));
              }
             
              // use this method to access a product by its index (order) within the database. This would correspond roughly to a primary key within a proper database
              this.getProdByIndex = function (whichIndex){
                   return (this.productArray[whichIndex]);
              }
             
              // use this method to access the product by name. You could easily clone this function to search on some other attribute, such as prodID.
              this.getProdByName = function (whatName){
                   for (i in this.productArray){ if (this.productArray[i].prodName == whatName) return this.productArray[i] }
                   return undef();
              }
         }
         
         
         // the Product Object constructor
         function Product(prodID, price, prodName, desc, prodImage){
              this.prodID = prodID;
              this.price = price;
              this.prodName = prodName;
              this.prodDesc = desc;
              this.prodImage = new Image(); this.prodImage.ImageUrl = prodImage;
             
              return (this);
         }


----------

Garmon Sutrix


Notice from miCRoSCoPiC^eaRthLinG:
When posting large-ish blocks of code make sure you enclose them between CODE or CODEBOX tags. Since you're new - you're being notified of this. The usage of CODE/CODEBOX is absolutely necessary for our Credits System to perform the calculations properly. Omittance of this tag in future might cause you to loose the entire credits gained for a particular post.

 

 

 


Reply

wildsky
Very nice tutorial!! That really made it all clear.

One big question though. Once you have implemented a solution like that, how would sort your 'database'? For example, how could I sort my products by price?

Chris

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

Recent Queries:-
  1. favascript object database - 278.60 hr back. (1)
Similar Topics

Keywords : garmons, javascript, 1, simple, object, database, learn, basic, object, oriented, programming

  1. Conditional Statements Of Javascript
    Tutorial for beginers (1)
  2. Javascript Operators
    (0)
    In this part of the tutorial, we will discuss about JavaScript Arithmetic Operators, JavaScript
    Assignment Operators, Comparison Operators, Logical operators and conditional operator. +, -, *, /
    etc are the JavaScript Arithmetic Operators. =, +=, -= etc are the JavaScript Assignment Operators.
    ==, != etc are the Comparison Operators and “&&”, “||” etc are the Logical
    operators. Arithmetic operators are used to perform arithmetic between variables and/or values and
    Assignment operators are used to assign values to JavaScript variables. Comparison o....
  3. Javascript Tutorial For Beginner
    Using Javascript in HTML page (0)
    In this tutorial I will show you how you can put JavaScript in a HTML page. It is very easy to add
    JavaScript in a HTML page. We will use tag for this purpose. Inside the tag, we will use "type="
    attribute and will define the scripting language. We will define the script language as
    “text/javascript”. After define the script language we will add our JavaScript codes and
    at last we will close the tag using . So the complete code will be- CODE (Place for our
    JavaScript codes) Now we will use “document.write” command (it i....
  4. Is Their A Free Or Express Program To Help Make Javascript, Or How Do I Do It.
    i want to make javascript but dont know how. (0)
    can someone direct me to a free program that will help me make java script, or maybe just tell me
    how? ....
  5. Javascript SSI- Blocking Internet Protocols
    Blocking Internet Protocals from site (2)
    Hello, i thought this would be interesting since i haven't discussed Javascript in years.
    SSI(Server Side Includes) can be used for many interesting things...many of which deal with
    connection information and such. A few years ago i was working on something for the Counter-Strike
    Blacklist when it existed. It was a project i was making for a site called CS anti-hack Community.
    This was going to be an all web-based security project to basically not allow any IP currently on
    the blacklist to preceed to any site that wanted to be a part the anti-hack community. Well....
  6. Forum post templates!
    Using javascript (3)
    I guess I'll better start by explaining by what I mean by these post templates. The idea came
    to me as one online-friend of mine has a habit of posting all his posts with same colour on a
    certain forum. We had previously talked how it would be cool if vBulletin (in this case) would have
    option to save a "post template" which it would automatically load to textarea everytime a new reply
    or thread is posted. Well as it is not implemented on the server side, why not do it clientside!
    What you may have not realized is that "bookmark toolbar" or "personal bar" bookmark....

    1. Looking for garmons, javascript, 1, simple, object, database, learn, basic, object, oriented, programming






*SIMILAR VIDEOS*
Searching Video's for garmons, javascript, 1, simple, object, database, learn, basic, object, oriented, programming
advertisement




Garmon's Javascript #1 - Simple Object Database - Learn basic Object-Oriented Programming