Forum Discussion

howie_'s avatar
howie_
Contributor
12 years ago

JScript nested functions

Hello, 



I'm trying to approximate a "class" in jscript, with member functions. I'd like to do something like the code below. Does anyone know if it's possible?



 



function Thing()

{

     this.Items = new Array("10", "20", "30");



     function Find(item)

     {

            //search Items for "item"

     }

}





var thing = new Thing();



thing.Find("10"); 
  • Philip_Baird's avatar
    Philip_Baird
    Community Expert
    Hi Howie, in order to approximate classes in JScript, I have used Dean Edwards Base.js which, in my view, simplifies defining classes as well as providing an extend() function which makes inheritance a breeze, e.g.



    A base Class:


    var Thing = Base.extend( {


      constructor: function() {


        this.Items = new Array( "10", "20", "30" );


      },


      Items: null,


      Find: function( itemToFind ) {


         for ( var j = 0; j < this.Items.length; j++ )


          if ( this.Items[ j ] === itemToFind ) {


             return j;


          }


        return -1; 


      }


    } );



    A sub class:


    var It = Thing.extend( {


      constructor: function( name ) {


        this.base();


        this.Name = name;


      },


      Name: null,


      GetName: function() {


        return this.Name || "I am nameless";


      }


    } );




    In order to import the Base.js file into Test Complete, I simply changed the extension from .js to .sj and added as an Existing Item.

    This does, of course, need the appropriate //USEUNIT statement to include the Script Unit containing Base at the head of the Script Unit in which the classes are defined



    I have used Base.js for the following reasons:


    1. It is easy to use


    2. It is standalone where other, similar class libraries are part of a larger library such as JQuery


  • Yes, sure.



    Here pieces of working code:






    function tstClass()


    {


      this.items = [ "10", "20", "30" ];


      this.find = function( itemToFind )


      {


        for ( var i = 0; i < this.items.length; i++ )


          if ( this.items[ i ] == itemToFind )


             return i; 


        return -1;  


      }


    }


     


    function tstObj()


    {


      var thing = new tstClass();


      var result = thing.find( "10" );


      if ( result == -1 )


        Log.Message( "Item not found" );


      else


        Log.Message( "Item found at position " + result );


    }





    if you want not to expose array in your object, make it local in object constructor (remove this. prefix in all array references and define it as local variable).