Link to home
Create AccountLog in
Avatar of webfullcircle
webfullcircleFlag for United States of America

asked on

How do I develop and use classes in Javascript?

Hi!

I am developing a small library of functions. There may be a need where these functions could potentially interfere with each other so I need to put them into a class which than can be given an instance of.

Question is, How do I do it? And then how do I use the class?
I tried doing something like this but it does not work...
---- in the .js file ----
 
class JsLib
{
  public function Func1 ()
  {
    document.write("hello");
  }
  public function Func2 ()
  {
    document.write("bye");
  }   
}
 
 
 
--- in html, the .js is included, then ---
<script type="text/javascript>
function Exec()
{
   var a = new JsLib();
   a.Func1();
   a.Func2();
}
</script>
<a href="javascript:Exec();">test</a>

Open in new window

Avatar of hielo
hielo
Flag of Wallis and Futuna image

There is no "class" keyword. You use a "regular" function for a constructor and declare the public variable with the "this" keyword. Refer to the following:
http://mckoss.com/jscript/object.htm
function class_myStuff() {

      this.variable1 = "hey there";

      this.convertToString = function (string) {
            //do stuff
            return string
      }
      
      this.doMoreStuff = function () {
      
      }
}

var myStuff = new class_myStuff();
Avatar of webfullcircle

ASKER

2MMDeveloper:

so then I can access the class like ?
myStuff.doMoreStuff();

Open in new window

>>so then I can access the class like ?
Not your "class" - Your class object. So yes, you can access it as:
myStuff.doMoreStuff();

Read the link provided.
yep... here's a class file I wrote for work that may help you out

http://mmdeveloper.selfip.com/temp/work/nefec/


fordmJS.js.txt
Ok, tried something similar, now the error console is giving me

Error: FadeOut is not defined
Source File: file:///C:/Documents%20and%20Settings/*/Desktop/ss2.js
Line: 79


This is what I have. This is basically a slideshow script that will fade in/out images.
function JSS() {
 
    /* Main configuration */
 
    this.sWidth = "640";     // Slideshow dimensions
    this.sHeight = "480";
    this.Units = "px";      // the dimension units to use, any CSS2-compliant (pt, px, em, %, etc...)
    this.Pictures = Array();   // pictures array, see below to populate
    this.pShowDelay = 3000;      // time of how long the picture is shown, in milliseconds
    this.AniDelay = 10;        // Delay between each step of alpha, in milliseconds. The lower, the faster
    this.DivCssClass = "";        // Set the CSS class of the div container
    this.ImgCssClass = "";        // Set the CSS class of the image
    this.AniStep = 0.01;      // Alpha percentage step
    this.OverlayColour = "#000000"; // overlay colour which is faded into
    this.InitialOpacity = 1;       // Set the initial opacity of the first image
    this.debug = true;     // turn debugging on or off
    this.index = 0;         // index of the currently shown pic. Set to 0 for first pic.
 
    /* End of main configuration!! */
 
    this.rnd; // generate a random instance
    this.iT; // timer id
    this.iT2;
    this.delay = false;
    this.Opacity;
 
 
    /* Initialize the slideshow */
    this.Init = function() {
 
        /* Place the required initial images here!! */
        this.Pictures.push(">@>30   09.jpg"); // add first image
        this.Pictures.push("12-O H:>;0 ?>74=> 25G5@><.jpg"); // second image
        this.Pictures.push("Latskova_St_.jpg");
 
        //Pictures.push("/images/image2.jpg"); // Template for adding more images!
 
 
        this.rnd = Math.random().toString().replace(".", ""); //this will generate us a random id we can use
        document.write('<div id=\'jss_' + this.rnd + '\' style="background-color: ' + this.OverlayColour + '; width: ' + this.sWidth + this.Units + '; height: ' + this.sHeight + this.Units + ';"');
        if (this.DivCssClass != "") document.write(" class=\"" + this.DivCssClass + "\">"); else document.write(">");
        document.write('<img id=\'jss_i' + this.rnd + '\' style="float: left; width: ' + this.sWidth + this.Units + '; height: ' + this.sHeight + this.Units + ';" src="' + this.Pictures[this.index] + '"');
        if (this.ImgCssClass != "") document.write(" class=\"" + this.ImgCssClass + "\" />"); else document.write(" />");
        if (this.debug) {
            document.write("<br />O: <span id='debug'>debug</span>");
            document.write("<br />I: <span id='debug_index'>debug</span>");
        }
        document.write('</div>');
        if (this.debug) { setInterval("this.Debug()", 50); }
        this.Opacity = this.InitialOpacity;
        this.PerformFadeOut();
    }
 
    /* Adds the picture to the slideshow queue with the specified relative or absolute url */
    this.AddPic = function(url) {
        this.Pictures.push(url);
    }
 
    /* Executed on debug, do not use normally */
    this.Debug = function() {
        document.getElementById("debug").innerHTML = this.Opacity.toString();
        document.getElementById("debug_index").innerHTML = this.index.toString();
        return true
    }
 
    /* Performs the fading out sequence */
    this.PerformFadeOut = function() {
        this.iT = setInterval("FadeOut()", this.AniDelay);
    }
 
    /* Delays the displayed picture */
    this.DelayPic = function() {
        if (this.delay) { clearInterval(this.iT2); this.delay = false; this.PerformFadeOut(); } else this.delay = true;
    }
 
    /* Fades out one step */
    this.FadeOut = function() {
        this.Opacity = this.Opacity - this.AniStep;
        document.getElementById("jss_i" + this.rnd).style.opacity = this.Opacity;
        if (this.Opacity <= 0.1) { clearInterval(this.iT); this.Opacity = 0; this.PerformFadeIn(); }
    }
 
    /* Fades in one step */
    this.FadeIn = function() {
        Opacity = Opacity + AniStep;
        document.getElementById("jss_i" + rnd).style.opacity = Opacity;
        if (Opacity >= 1.0) { clearInterval(iT); iT2 = setInterval("DelayPic()", parseInt(pShowDelay / 2)); Opacity = 1; }
    }
 
    /* Performs fading in sequence */
    this.PerformFadeIn = function() {
        if (index < Pictures.length - 1) {
            index++;
            document.getElementById("jss_i" + rnd).setAttribute("src", Pictures[index]);
        } else { index = 0; document.getElementById("jss_i" + rnd).setAttribute("src", Pictures[index]); }
        iT = setInterval("FadeIn()", AniDelay);
    }
}

Open in new window

At just a quick glance, I see you are using this within setInterval, clearInterval, etc.  When you use those functions, the 'this' keyword no longer refers to your class, but the window object instead.
ok I'm going to assume you called the object reference JSS, such as:

var class_JSS = new JSS();


I'd try either:

setInterval("this.FadeOut

OR

setInterval("class_JSS.FadeOut
I am using like this
 var s = new JSS();
        s.Init();
       
I tried using this.Fadeout like you've said but it still does not work.


        if (this.debug) { setInterval("this.Debug()", 50); }

Open in new window

Scope is a common problem and misconception with starting as well as advanced javascripters. The problem being that 'this' is a rather ambiguous concept in javascript, which has to do with it's extensible nature mostly.

So, if we cannot rely on this, the question would arise, how do I get access to my 'Object' from within a method that runs under a different scope. And this is where the 'scope' of a script becomes a very interesting subject. Whenever a function gets called 'this' will only relate to some Object that it's called from as a method of that Object, but it also retains a scope of when it originally got declared. Within this scope the function will have access to any variable declared at a 'higher' level.

How do we make use of scope in your particular situation? We declare a variable to be 'this'. The new variable will be included in the scope of any function we create afterwards within the same method, and anything that gets called from within this new function will also have access to the scope we have just 'created'.

In the Code Snippet I've created the scope and anonymous function that you would need. As you can see FadeOut now gets called as a method of 'self'. Because self is a reference to the Object (JSS instance) you've created the method FadeOut can now reference the instance of JSS as 'this'.

Since this rather long post is actually closures in a nutshell I really recommend reading more on it elsewhere on the web, for instance at http://www.jibbering.com/faq/faq_notes/closures.html
    /* Performs the fading out sequence */
    this.PerformFadeOut = function() {
        var self = this;
        this.iT = setInterval(function() {
            self.FadeOut();
        }, this.AniDelay);
    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of GoofyDawg
GoofyDawg
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
I thought the new JS WOULD have the class keyword - or was it shelved?

http://www.mozilla.org/js/language/js20-1999-02-18/classes.html
If any browser would go for implementing JS2 it'd open up a whole storm of cool new features in that one particular browser, but living in a world where a dominating leader takes 10 years before they bother to seriously update their browser-engine (no, I don't think the few patches MS made and called 5.x or 6.x count for anything here) it's a little hard to rely on any serious new technology.

So, in effect, it was shelved... Although perhaps in flash you can use all of that, if I'm not mistaken Flash uses ecma-script 2 or even 3 as their basis :)

Mind you, I have not taken a serious look at the ecma-script specs for years, so I'm not even sure if Class is still part of that, I do know operator overloading is in there, and some other cool little gems :)
Thank you! It worked! I am just used to C# programming and never went into doing OOP in javascript.
Thank You all for your replies, I just never got around to do OOP in javascript; been doing mostly C#