ActionScript 2
every class is a function and every function a class ... AS2 is prototype based ...
trace.prototype = { };
var f = trace;
trace(new f());//will yield [object Object]
accessing Function::prototype
allows extending classes at runtime:
MovieClip.prototype.moo = function () {
trace(this+" says 'moooooooo' ...");
}
_root.moo();//_level0 says 'moooooooo' ...
Object::__proto__
... allows you to change the prototype of an object, which can be used for runtime reclassing:
var o = trace;
o.__proto__ = [];
trace(o.push("foo", "bar", "foobar"));//3 here
trace(o.length);//also 3
trace(o[1]);//bar
in this example, the function trace
is reclassed to Array ... pretty cool, huh? :)
Function::apply
and Function::call
allow applying any function as a method to any object:
Array.prototype.push.apply(trace,[1,2,3]);
trace(trace.length);//3
trace(Array.prototype.splice.call(trace, 1,1));//2 ... actually, this is [2] (the array containing 2)
using the three above, instantiation of a class MyClass
with parameters param_1, ..., param_n
can be written as:
var instance = {};
instance.__proto__ = MyClass.prototype;
MyClass.call(instance, param_1, ..., param_n);
a corelation of Function::push
and Function::apply
is that this
is simply a function argument, that is passed automatically ... as any other function argument, it can be written to ...
var f:Function = function () {
this = [];
this.push(1,2,3);
trace(this);//1,2,3
this = _root;
trace(this);//_level0
}
f();
Object::__resolve
... settings this method allows you to react to lookups on undefined properties ... this is fun and useful for proxying, mocking, composition, delegation, and so on ...
import mx.utils.Delegate;
var jack:Carpenter = ...
var jim:BlackSmith = ...
...
var guys:Array = [jack, jim, ...]
var o = { __resolve : function (name:String) {
for (var i:Number = 0; i < guys.length; i++) {
var guy = guys[i];
if (guy.hasOwnProperty(name)) {
var ret = guy[name];
if (ret instanceof Function) {
ret = Delegate.create(guy, return);
}
return return;
}
}
return "sorry man, but nobody knows, what '" + name + "' means";
});
//some really imaginary stuff (i hope it makes the point):
trace(o.saw);//[object Hammer]
trace(o.anvil);//[object Anvil]
trace(o.ventilator);//"sorry man, but nobody knows, what 'ventilator' means"
trace(o.makeSword());//[object Sword]
that's it for now ... there's an awfull lot more ... the thing is simply, that AS2 is an exiting language, but painfully slow ... AS3 in comparison is boring as hell, but the speed increase is really great ...