A couple of Prototype Ports for ActionScript





1
Date Submitted Fri. Jan. 11th, 2008 11:35 PM
Revision 1 of 1
Helper Fordiman
Tags ActionScript | Bind | curry | JavaScript | Prototype
Comments 1 comments
Ok, so here's the deal. I've started to dally with Flash a bit, and I'm feeling all naked without my nifty Prototype functionality.

Most important to me are the bind() and curry() functions (though, others will rear their heads as my AS code gets more complex), Object.extend, and $A. They are para-ported here.

function $A(a):Array {
        var r=[];
        for (var i=0; i<a.length; i++) {
                r.push(a[i]);
        }
        return r;
}
/*Unfortunately, I can't seem to declare this to Object.extend.
 So, next best thing: Obj.extend (and whatever else I have to port
 from Prototype)*/

var Obj = {
        extend: function (d,s):Function {
                for (var i in s) d[i]=s[i];
                return d;
        }
}

Obj.extend(Function.prototype, {
        bind: function(boundContext /*, arguments... */):Function {
                /* It's an odd thing; AS complains when I
                use the same variable names in different functions.
                annoying, that. */

                var
                        boundFunction:Function = this,
                        boundArguments:Array = $A(arguments),
                        boundContext = boundArguments.shift();
                return function():void {
                        boundFunction.apply(
                                boundContext,
                                boundArguments.concat($A(arguments))
                        );
                }
        },
        curry: function(/* arguments... */):Function {
                var
                        curriedMethod:Function = this,
                        curriedArguments:Array = $A(arguments);
                return function():void {
                        curriedMethod.apply(
                                curriedMethod,
                                curriedArguments.concat($A(arguments))
                        );
                }
        }
});
/* A little example of use */
var test = function (a):Function {
        //Just throws an error, so we can get immediate feedback.
        throw new Error(a);
}
var test1 = test.curry('It works!');
test1();
 

Bryan Elliott

Comments

Comments AS != JS
Wed. Apr. 2nd, 2008 2:59 PM    Scripter sehrgut

Voting

Votes Up


Helper Fordiman
Newbie stronciy

Votes Down


Scripter sehrgut