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:
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: 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: var myNewObj2 = new MyObject("Hello World!!");
And receive the parameters in the object constructor like this: 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: function MyObject(){ this.colour = "blue"; this.itemType = "widget";}
Later, you can access these properties like this: 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: function MyObject(userColour, userType){ this.colour = userColour; this.itemType = userType;}
And create a couple of instances like this: 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: 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. // 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.