Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I look at structuring my JavaScript?

Tags:

javascript

I'm having a little trouble working out how my JavaScript should be structured, etc.. My OOP skills in languages such as PHP, ActionScript 3 and so on are what I'm assuming to be on-par, but JS is lacking this which has thrown me off quite a bit in my learning.

I have a vague understanding of the prototype feature which I used a little in AS2 - I believe this is the closest I'll be able to get. At the moment, I'm laying out my code similar to this:

var slideshow = 
{
    property: value,

    /**
     * This is a method
     */
    myMethod: function()
    {
        // do method things
    }
};

// ------
slideshow.property ++;
slideshow.myMethod();

This all works okay, but it's void my ability to do something like:

var myslideshow1 = new Slideshow();
var myslideshow2 = new Slideshow();

myslideshow1.property = 10;
myslideshow2.property = 16;
  1. I'm not sure on how to go about creating two different instances of one "object" I've created (in this case, slideshow).
  2. I can't find any resources that explain the prototype feature in a way that makes sense.

Any pointers would be supoib.

like image 531
Marty Avatar asked Apr 28 '11 01:04

Marty


2 Answers

Any javascript function can act as a constructor for a class, so try this:

function SlideShow(params) {
    return { 
        property: value,
        myMethod: function() {
            //do method things
        };
    };
};
var slideshow1 = new SlideShow(params);
slideshow1.property = 10;
//etc. 
like image 124
Thomas Shields Avatar answered Nov 08 '22 14:11

Thomas Shields


I would frown apon using prototype to add methods to a class as there could be performance issues

Here is a sample class structure you could use. JavaScript classes are not much different the functions.

function MyItem(){
  this.d = '';
  this.clear = function( ) {
    this.d = '';
  }
}
var myItem = new MyItem( )
myItem.d = "test";
alert(myItem.d);
myItem.clear();
alert(myItem.d)

Some good reading here

like image 2
The_asMan Avatar answered Nov 08 '22 15:11

The_asMan