Search Unity

Javascript constructors?

Discussion in 'Scripting' started by bronxbomber92, Nov 20, 2007.

  1. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888
    Hi, I was wondering if the constructors for classes work the same as they do in C# or C++?

    e.g.
    Code (csharp):
    1. class Example
    2. {
    3.      function Example( bleh : float )
    4.      {
    5.           memberVar = bleh;
    6.      }
    7.      
    8.      var memverVar : float;
    9. }
    10.  
    11. ...
    12. Example example( 1.0 );
    How does scope work also? Is the default scope public or private? Do I have to use the private/public keyword for each method/member variable or is it like C++?
     
  2. shawn

    shawn

    Unity Technologies

    Joined:
    Aug 4, 2007
    Posts:
    552
    This is how I write standalone javascript classes in Unity.

    Code (csharp):
    1.  
    2. class Example extends System.Object
    3. {
    4.    private var privVariable:float;
    5.    var variable:float;
    6.    
    7.    function Example(input:float)
    8.    {
    9.       variable = input;
    10.       privVariable = input;
    11.    }
    12.  
    13.    private function DoSomething()
    14.    {
    15.       // Do Stuff ...
    16.    }
    17. }
    18.  
    19.  
    20. ...
    21.  
    22. var instance:Example = new Example(1.5);
    23.  
    Everything defaults to public in unity javascript. You need to specify private if you wish it to be a private method/member.
     
  3. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888