SitePoint Sponsor

User Tag List

Results 1 to 9 of 9
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2005
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript Static Classes

    Hi again:

    I'm trying to use the functionality of Java static classes in Javascript, and such things as a singleton.

    Can i do this in Javascript?

    Thanks.

  2. #2
    SitePoint Guru
    Join Date
    Feb 2005
    Posts
    602
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Static stuff in JS is easy, but public/private distinction isn't (and results in very messy code). Here's a sample singleton class:

    Code:
    function Singleton() {
    	//stuff
    }
    
    Singleton.instance = null;
    
    Singleton.getInstance() {
    	if (!this.instance)
    		this.instance = new Singleton();
    	return this.instance;
    }
    The key thing to remember is that JS is a prototype-oriented language.
    Last edited by Maian; Apr 15, 2005 at 01:00.

  3. #3
    SitePoint Enthusiast
    Join Date
    Apr 2005
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've tryed something similar, but i was getting errors when invoking methods on it. I was doing it by using

    Code:
    function gKeys(){
    	this.Processo=null;
    	gKeys.getProcesso=function(){
    		if(this.Processo!=null)
    			return this.Processo;
    		else
    			return "something else";
    	}
    	
    }
    and when i invoke it as a static method,

    Code:
    var prk=gKeys.getProcesso();
    i get

    Error: gKeys.getProcesso is not a function

    What am i doing wrong?

    Thanks.

  4. #4
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    JS is pretty powerful, and because there aren't types to worry about and because of its flexibility, it doesn't seem like there are many rules. So, you're only limited by your imagination. I'm not sure what you are referring to when you say you want a "static class", but you can certainly create static functions and variables in javascript.

    Static functions and variables:
    In js, a constructor function defines a class. To create constructor function, you do this:
    Code:
    function Apple(p1, p2)  //constructor function
    { 
    	this.size = p1;
    	this.color = p2;
    }
    
    var myApple = new Apple(5, "red"); //create new Apple object
    alert(myApple.color);
    In js, a function is an object, and in js you can attach functions and properties to an object at will:
    Code:
    Apple.greeting = function(){alert("hello")};  //assign anonymous function to Apple
    Apple.greeting();  //static function call
    Singleton pattern:
    Quote Originally Posted by Maian
    Here's a sample singleton class:
    Code:
    function Singleton() {
    	//stuff
    }
    
    Singleton.instance = null;
    
    Singleton.getInstance() {
    	if (!this.instance)
    		this.instance = new Singleton();
    	return this.instance;
    }
    The problem with that is you can always make another instance like this:

    var Singleton2 = new Singleton();

    So, that isn't much of a Singleton class. I'm not sure a Singleton class has much meaning in js, but see if this works for you:

    Step 1: get rid of the name of the constructor function and make it anonymous:

    Code:
    function () //constructor function
    { 
    	this.size = 5;
    	this.color = "red";
    }
    Step 2: use new to create an object and get a reference to it:
    Code:
    var SingletonApple = new function () 
    { 
    	this.size = 5;
    	this.color = "red";
    };
    No more objects of the class can be created because there is no way to refer to the constructor function. In js, you can also create objects without a constructor function:
    Code:
    var singletonObj = {"size":5, "color":"red", "greeting":function(){alert("hello")} };
    singletonObj.greeting();
    Last edited by 7stud; Apr 15, 2005 at 01:56.

  5. #5
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    var prk=gKeys.getProcesso();
    i get

    Error: gKeys.getProcesso is not a function

    What am i doing wrong?

    Thanks.
    getProcesso isn't created and attached to the gKeys object until after the gKeys function is executed. You need to do this:
    Code:
    gKeys();
    var prk=gKeys.getProcesso()

  6. #6
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    amsmota

    There are no classes, no class declarations, no class members and no class inheritance in javascript. Although this language sounds and looks like Java, it's totally different. This article (and others on that site) should shed some light:

    http://www.crockford.com/javascript/javascript.html

    Some examples how common java patterns can be implemented in JS:

    Code:
    function Foo () {
    	this.publicMember = "..."
    	var privateMember = "..."
    	Foo.classMember = "..."
    }
    Foo.classMethod = function() {
    	alert("classMethod")
    }
    Foo.prototype.instanceMethod = function() {
    	alert("instanceMethod")
    }
    var bar = new Foo()
    bar.instanceMethod()
    Foo.classMethod();
    bar.constructor.classMethod()
    and this is how to create Singleton wrapper for any "class":

    Code:
    function Singleton(aClass) {
    	return aClass.__singleInstance || 
    		(aClass.__singleInstance = new aClass());
    }
    All calls to Singleton(someClass) will return the same object of given class:

    Code:
    function Foo() {
    	this.number = Foo.count = (Foo.count || 0) + 1;
    }
    
    var f1 = new Foo();
    alert("new instance #" + f1.number)
    
    var s = Singleton(Foo);
    alert("singleton #" + s.number)
    
    // lets create some more
    new Foo(); new Foo(); new Foo();
    new Foo(); new Foo(); new Foo();
    
    var f2 = new Foo();
    alert("new instance #" + f2.number)
    
    var s2 = Singleton(Foo);
    alert("singleton is still #" + s2.number);

  7. #7
    SitePoint Guru
    Join Date
    Feb 2005
    Posts
    602
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    7stud, you're right about my sample singleton being easy to break, but how is your example a singleton? It can easily be copied but using that object as a prototype - for ex:

    var SingletonCopier = function();
    SingletonCopier.prototype = SingletonApple;
    var SingletonCopy = new SingletonCopier();

    Besides, it's also not lazy (only constructed when needed).

  8. #8
    SitePoint Enthusiast
    Join Date
    Apr 2005
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Gee, too much information for me to grasp at the moment. I'm getting what i want by using

    Code:
    var gKeys = new function(){
    	this.Processo=null;
    	this.getProcesso=function(){
    		if(this.Processo!=null)
    			return this.Processo;
    		else
    			return tgrid.currentRow().attributes["prk"].value;
    	}
    }
    and then

    Code:
    gKeys.getProcesso()
    but i'm going to check your responses cause i have a lot more uses for that.

    Thanks a lot to all.

  9. #9
    SitePoint Addict
    Join Date
    Mar 2005
    Posts
    214
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by amsmota
    Hi again:

    I'm trying to use the functionality of Java static classes in Javascript, and such things as a singleton.

    Can i do this in Javascript?

    Thanks.
    This is my "eager" singleton version ("eager" by opposition to what is known as "lazy instantation") which "autoboots"
    one can compare with the normal class version here, slight but subtil difference only: see the "()" at the end of constructor definition
    http://www.sitepoint.com/forums/showthread.php?t=253773
    Code:
    <script type="text/javascript">
    <!--
    /***************************************************************
    * "Eager" Singleton Version: Instantiation at boot
    * see the "()" at the end of constructor definition
    ***************************************************************/ 
    var Singleton = function() {
        /***************************************************************
        * private member: can only be accessed 
        * by getter and setter methods
        ***************************************************************/ 
       var Message;    
    
        /***************************************************************
        * getter and setter methods: can access private members 
        * can be called by external functions
        ***************************************************************/    
       this.getMessage = function() {          
            return Message;
       }
       
       this.setMessage = function(s_message) {        
            Message = s_message;
            return Message;
       }
       return this
    }();
    //-->
    </script> 
    
    <script type="text/javascript">
    <!--
    Singleton.setMessage("I am a singleton");
    
    var Message = Singleton.getMessage();
    alert(Message);    
    //-->
    </script>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •