Archive for the ‘Javascript’ Category

Fantom’s History and Future with JavaScript

Wednesday, June 2nd, 2010

One of Fantom’s primary design goals from day one was portability between the JVM and CLR. Naturally we got to thinking, if we can run on both of the popular VM’s, why not on JavaScript too? That would enable enormous opportunities for code reuse and greatly simplify the huge impedance mismatch of developing backend server code and user interfaces in the browser.

Read the full post at Fantom.org

JavaScript try-catch bug?

Wednesday, January 13th, 2010

Ran across a seemingly bad bug either in Rhino or JavaScript language spec – haven’t had a chance to dig into. But this pattern appears to let an exception raised in func() leak thru the surrounding try block:

  function foo()
  {
    try { return func(); }
    catch (err) { ... }
  }

I was able to work around by assigning to a local variable:

  function foo()
  {
    try { var x = func(); return x; }
    catch (err) { ... }
  }

Did a short Google on this, but nothing obvious turned up.

Static Typing

Sunday, July 26th, 2009

I’m not big on comparing the merits of different languages. Every language I’ve used serves a good purpose for some task. So I generally pick the best language for the task at hand.

In general, though, I always tend to prefer static languages for anything but a small or quick and dirty project. Especially when its a code base I intend to maintain for some time.

I just spent the weekend refactoring Fan’s JavaScript compiler to change how I model Fan fields in JavaScript. The way I had previously done it looked like this:

// Fan
class Foo { Int x := 5 }

// JavaScript
Foo.prototype.x$get = function() { return this.x; }
Foo.prototype.x$set = function(val) { this.x = val; }
Foo.prototype.x = 5;

Which isn’t great, but didn’t really have alot of options. But it seemed nice enough. It grouped the accessors and storage neatly together. And in most cases, since I can access the storage directly, the code overall was fairly clean.

Unfortunately that model made it very difficult to make certain use cases of fields and methods work (like overriding a const field with a method). So I changed the JavaScript to look like this:

// Fan
class Foo { Int x := 5 }

// JavaScript
Foo.prototype.x = function() { return this.m_x; }
Foo.prototype.x$ = function(val) { this.m_x = val; }
Foo.prototype.m_x = 5;

That change would have been a bit painful in any language, since there was just alot of code to update (the sys library and all the native implementations are written directly in JavaScript).

However, since JavaScript does not have static type checking, I pretty much had to tackle errors one-by-one using the test suite and Fresco (the web UI I’m developing at SkyFoundry).

This is probably the biggest reason I prefer static languages. When you have to make sweeping changes on a large code base, you simply can’t verify your changes 100% in any language. But a compiler with static type checking can help you tremendously. Especially for code that is difficult to unit test, like UIs.

Mounting a JavaFX applet from Javascript

Wednesday, July 1st, 2009

There’s not a whole lot of documentation surrounding the Javascript deployment scripts the new Java Plug-in and JavaFX use (actually I couldn’t find any). Luckily if you beautify the minimized code, its not too hard to figure out how things tick.

Out of the box, those scripts use document.write in place, which makes them very problematic if the script is not inlined in the initial HTML page. Trying to call them after the page is loaded will just nuke your document.

Luckily there’s a function (javaFxString) in the dtfx.js script that serializes the necessary code to a string which you can use:

var s = javafxString({
          codebase: "/s/fwt/javafx/dist/",
          archive: "Canvas.jar",
          draggable: true,
          width:  200,
          height: 200,
          code: "fan.fwt.Canvas",
          name: "Canvas",
          id: "app"
      });
someElement.innerHTML = s;

This will let you insert the JavaFx applet code anywhere in your DOM. I only tried this in IE8 so far (since this is a workaround for IE-only). But I assume this should work in all browsers.

Javascript Bitshift Performance

Tuesday, June 16th, 2009

While working on 64-bit integer support in Javascript for Fan, I ran across a blurb about bit shift performance of Numbers. The basic gist was, since Javascript has to convert the number to an integer, perform the op, then convert back, multiplying or dividing by a power of two should be as fast, or faster. On the surface that might make sense, but I wanted to see for myself, so I hacked up a very naive test case:

var x = 0xffff;

var s = new Date().getTime();
for (var i=0; i<100000; i++) x = x >> 2;
var e = new Date().getTime();
var res1 = (e-s);
   
s = new Date().getTime();    
for (var i=0; i<100000; i++) x = x / 4;
e = new Date().getTime();
var res2 = (e-s); 
   
alert(">> " + res1 + "ms\n" + "/  " + res2 + "ms");

Very unscientific results:

Browser               >> 2    / 4
--------------------  ------  -------
Chrome 2.0.172.31     2-3ms   4-7ms
Firefox 3.0.11 (win)  11ms    15-16ms
Safari 3.1 (win)      15ms    15ms
IE8                   63ms    62-78ms
Opera 9.64 (win)      46ms    63ms

Interesting to see the different performance b/w browsers, but also seems clear, overall, the bit-shift operators perform slightly better even with the box/unbox hit.

Extending built-in types

Tuesday, June 2nd, 2009

I ran into an issue where I really needed to tag the built-in Javascript types with additional information to make Fan work better.  The big one is annotating a Number to be either a Int or Float, which you need to do to make all the equality checks work consistently (since 5 != 5f).

This is was my first attempt, which I assumed would work:

>>> var x = 15;
>>> x.$fanType = sys_Type.find("sys::Int");
>>> x.$fanType
undefined

But no dice.  After a bit of googling, I found this page, which says in order to add properties to the built-in types, you must create objects using the constructor syntax:

>>> var x = new Number(15);
>>> x.$fanType = sys_Type.find("sys::Int");
>>> x.$fanType
"sys::Int"

I assume this a performance optimization, where you can use a primitive int value in the first case, and have to allocate an object in the latter. Though since Javascript is a pure-OO language, I would be interested in seeing how VMs actually implement this behavoir.

Edit 8 Jun 09: Just realized using the object syntax breaks equality checks for numbers:

>>> var x = new Number(4);
>>> var y = new Number(4);
>>> x == y
false

Which sort of sucks, but you can work around it using valueOf, but still annoying.

>>> x.valueOf() == y.valueOf()
true

Javascript Bitwise Operators

Friday, May 15th, 2009

I stumbled across an interesting “edge” case in Javascript when porting gfx to Javascript.

Turns out Javascript converts numbers to 32-bit signed numbers before evaluating bitwise operators.  This is problematic because it prevents you from using the msb for 32-bit bitmaks:

Java:        0xaabbcc | 0xff000000 = 0xffaabbcc (4289379276)
Javascript:  0xaabbcc | 0xff000000 = 0xffabbcc  (-554434)

The workaround is pretty straightforward, you simply have to add 2^32+1 to convert back to an “unsigned” value:

var x = 0xaabbcc | 0xff000000;
if (x < 0) x += 0xffffffff+1;

But unfortunately, that means I have to wrap all bitwise operations in a method call, and perform that check, which I expect will not be anywhere near as fast as the straight operator call.