views:

42

answers:

1

As some of you may know JScript.NET adds quite a few features to the common JavaScript language... it adds some class syntax, some type identifier etc etc..

The main reason I use JavaScript is because I love how dynamic it is, nested function calls, variables scope etc etc... All these features seem to work fine in the .NET version, however writing this sort of code gives me Type mismatch error:

public class Test extends Form {
    var btn : Button;

    function Test() {
        var anotherBtn  = new Button;
        anotherBtn.Text = "some text";

        // This is where the Type mismatch happens
        anotherBtn.add_Click(function(sender:Object, e:System.EventArgs) {
            Close();
        });

        this.Controls.Add(anotherBtn);
    }
}

Application.Run(new Test);

It seems like I can't pass anonymous functions like that. If I define the add_Click callback somewhere in the class, it works great!

How can I avoid this? I would like to code in JavaScript the way I'm always used to... can I somehow force the jsc.exe compiler to use an older version of JScript?

Or maybe functions inside a class are not regular JS functions? What's going on?

+1  A: 

Unfortunately, JScript anonymous functions aren't compatible with .NET delegates. As you said, methods of class aren't normal functions, because Microsoft wanted to make JScript classes compatible to every .NET class. It is a problem to do event handling in JScript.NET, Microsoft made it complicated and dumped developing this language :(

So unfortunately you have to comply with methods of event handling given by Microsoft. But you could make custom classes for these controls, which could behave as you would want.

With other controls is even harder than with WindowsForms controls, because these other controls require reference to delegate, which, as MSDN claims, aren't supported by JScript (I also couldn't make them work).

Sometimes the only way to set event handler is to make custom, extending class, which overloads method called by the event.

I hope you will find this answer useful.

UPDATE:

You mentioned in title to write applications in JScript 5.5 (or higher version). It is possible but in limited way. It is called "HTML Application", it is webpage run in special environment which gives to you permissions of local sandbox: you can manage files, read/write to Windows Registry, with external controls you can even use game controllers or use sockets to communicate by the Internet. But it still will be an interactive HTML page.

pepkin88
Thanks, this was helpful. I'll wait for some other input before marking you as accepted.
Luca Matteis