On 2009-09-18, at 06:49, Rami Ojares / AMG Oy wrote:

Hi,

I noticed the following difference between swf8 and swf9 runtimes.

Code:
var functionVar = someObject["method_name"]
functionVar(args)

This works in swf9 but not in swf8

But you can still call the function in swf8 using construct
someObject["method_name"](args)

Does anybody know what is going on in here?

You are seeing a feature that is added by ActionScript 3 (AS3 is the variant of Javascript supported by the swf9 player) that we cannot emulate in the LZX compiler called "method closures"[1]. In AS3 when you write an expression that returns a method of an instance, `this` in the method is a free variable, and the runtime will create a closure binding `this` to the instance used in computing the method. (Another equivalent model is that you are creating a partial evaluation of the method, binding the -1th argument `this` to the instance.) In Javascript (swf8, DHTML), no method closure is created. When you evaluate functionVar(args), it is as if you called the method with `this` unbound. In Javascript, when you call a function without binding `this`, it will be bound to the global object [2]. So, you can see that if your method refers to `this` at all, it will not work as expected.

The way to achieve the same effect in LZX is to say:

/* Helper function we should probably build in to LZX */
function createMethodClosure (instance, methodName) {
  return function () { return instance[methodName].apply(arguments); }
}

var functionVar = createMethodClosure(someObject, 'method_name');

functionVar(args);

---

[1]: It would be nearly impossible for the LZX compiler to make this transformation for you automatically, because Javascript is such a dynamic language. You really don't know until runtime that the expression `someObject["method_name"]` evaluates to a method and hence should create a method closure. In AS3, this is handled by the SWF runtime.

[2]: The designers of Javascript realize that this decision was a bad one. It is both functionally less useful, and a security flaw. It should be improved in EcmaScript 5 (and actually work in the "Harmony" release!)

Reply via email to