JScript.NET Quickstart

Table of Contents

Introduction

The following provides some quick hints on how to get up to speed on JScript.NET. It assumes you already know JScript 5.x. For information on JScript 5.x, please see the documentation on the Windows Script web site.

JScript.NET runs on top of the .NET platform, so can use the features of the .NET frameworks. It also runs a lot of existing script code (we don't have 100% compatibility) so you can do pretty much all the wonderful things you used to do in 5.x along with all this new cool stuff in 7.0.

JScript.NET can be used in ASP+ as well as for creating web services, .NET components (DLLs) and stand-alone EXE programs.

Where do I go for help?

For help about JScript.NET, have a look at the microsoft.public.net.jscript.general newsgroup.

For help about the .NET platform, see the NGWS SDK information that is installed as part of the .NET installation.

How do I install JScript.NET?

JScript.NET is installed as part of the .NET SDK, which you can install from http://msdn.microsoft.com/net/. Please note that the PDC release of the JScript.NET compiler is a very early version, and many things do not work yet. The beta release of the compiler will be much better!

How do I compile programs?

Using the jsc compiler. Type jsc /? for help -- the output is below. Note that the default thing for JScript to do is build a DLL; specify the /exe option to build an EXE

X:\>jsc /?
Microsoft (R) JScript Compiler Version 7.00.8946 [NGWS runtime 2000.14.2016]
Copyright (C) Microsoft Corp 2000. All rights reserved.

jsc [options] <source files> [[options] <source files>...]

Available compiler options:
  /?                 Display help
  /nologo            Do not display compiler copyright banner
  /warnaserror[+|-]  Treat warnings as errors
  /exe               Generate an executable
  /nostdlib[+|-]     Do not import standard library (mscorlib.dll)
  /debug[+|-]        Emit debugging information
  /w[arn]:<level>    Set warning level (0-4)
  /i[mport]:<file>   Import specified assembly
  /out:<file>        Specify name of binary output file
  /codepage:<id>     Use the specified code page id to open source files
  /lcid:<id>         Use the specified lcid for messages and default code page
  /clscompliant[+|-] Specify default for the assembly
  /versionsafe[+|-]  Specify default for members not marked 'override' or 'new'

How do I write 'Hello World'?

Easy:

  1. Create a file called hello.js
  2. Add the line print("Hello, World");
  3. From the command line, type in jsc /exe hello.js
  4. Run the output file hello.exe

How do I use types?

JScript.NET uses a colon to specify a type. Types can appear on variable declarations and in function definitions. The default type is Object, which can hold any of the other types.

var x; // x is of type Object
var y : int; // y is an integer; default value is 0
var s : String = "Hello, world"; // s is a string

function Area(i : int) : double
{
    // Area of a circle with radius 'i'
    return i * i * Math.PI;
}

JScript's built-in types include int, long, float, double, String, Object, Number, and Boolean. They map to the corresponding .NET types. JScript also has Array, Function, RegExp, and Error types that have no direct .NET equivalents.

You can also use any .NET type by importing the appropriate namespace.

How do I access a namespace?

Inside ASP+, you use the @import directive. When using the command-line compiler, you need to use the import statement. If the namespace is not part of mscorlib, you will also need to tell the compiler to access the assembly containing the namespace with an option such as jsc /exe /i:path\to\my.dll mycode.js

import System;

var x : DateTime = new DateTime(2000, 1, 1);
print(dt.ToString());

How do I create arrays?

You can create arrays using [] after the type name.

var nums : int[] = [1, 2, 3]; // array of integers
var chars : Char[];         // array of characters (NOT a string!)
chars = new Char[5];         // assign it a new array

You can still use old-style JScript arrays with the Array constructor, but presently the interaction between "native" arrays (those created with []) and JScript Arrays is not very good. We are working to improve this!

How do I create a class?

With the class statement. Inside a class you create fields and methods just as you would in classic JScript. The default access for class members is public.

class myClass
{
    var answer : int = 42;         // public field
    private var pi : double = Math.PI; // private field
    
    function sayHello() // public method
    {
        return "Hello";
    }
}

var c : myClass = new myClass;
print(c.sayHello() + ", the answer is " + c.answer);

How do I create properties?

JScript uses function get and function set to specify properties. You can specify either or both accessors to create read-only, write-only, or read-write properties. Currently, JScript properties cannot be parameterised.

class Person
{
    // person's name -- protected so derived classes
    // can see it
    protected var name : String;
    
    function get Name() : String
    {
        return this.name;
    }
    
    function set Name(newName : String)
    {
        if (newName == "")
            throw "You can't have a blank name!";
            
        this.name = newName;
    }
    
    function sayHello()
    {
        return this.name + " says 'Hello!'";
    }
}

var fred : Person = new Person();
fred.Name = "Fred";
print(fred.sayHello());

How do I inherit from another class?

Use the extends keyword. JScript can extend any CLS compliant class

// From the previous example
class Student extends Person
{
    // override a base-class method
    function sayHello()
    {
        return this.name + " is studying for finals.";
    }
}

var mary : Person = new Student;
mary.Name = "Mary";
print(mary.sayHello());

How do I implement an interface?

You can implement one or more interfaces using the implements keyword, followed by a comma-separated list of interfaces. Note that you can't declare an interface in JScript.NET, but you can use any CLS-compliant interface.

The following example shows how to implement IComparable to get a custom sort-order for an array of objects.

import System;

// A class which implements IComparable, and sorts
// strings based on their length
class MyString implements IComparable
{
    protected var str : String;

    function MyString(s : String)
    {
        str = s;
    }

    function ToString() : String
    {
        return str;
    }

    function CompareTo(other : Object) : int
    {
        var o : MyString = other;
        return (str.length - o.str.length);
    }
}

var strings : Object[] = new Object[5];
strings[0] = new MyString("Hello");
strings[1] = new MyString("Microsoft");
strings[2] = new MyString(".NET");
strings[3] = new MyString("A");
strings[4] = new MyString("JScript");

var i : int;

print("Original:\n");

for (i in strings)
    print(strings[i].ToString());

System.Array.Sort(strings);

print("----------\nSorted:\n");

for (i in strings)
    print(strings[i].ToString());

How do I specify custom attributes?

Put the at the start of the declaration. At the moment you have to use the long form (with ...Attribute at the end) but this requirement will soon be lifted. The following is a simple Web Service (ASMX) page:

<%@ page language="JScript" class="MyService"%>

import System.Web.Services;

class MyService extends WebService
{
    WebMethodAttribute function sayHello() : String
    {
        return "Hello from a JScript web service";
    }
}

Note that there are no commas or other separators between attributes.

How do I create an expando object?

If you just want a generic object to be expando, use the Object constructor. If you want one of your classes to be expando, specify the expando attribute

// A normal object, which is expando
var o = new Object();
o.expando = "this is an expando";
print(o.expando);

// An expando class.
expando class MyExpandoClass
{
    function Dump()
    {
        // print all the expando properties
        for (var x : String in this)
            print(x + " = " + this[x]);
    }
}

var e : MyExpandoClass = new MyExpandoClass();
e.foo = 42;
e.bar = "hello";
e.zak = new Date();
print("The contents of e are...");
e.Dump();