apply() workaround

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Christopher Benson-Manica

    #1

    apply() workaround

    IE 5.0 apparently does not support the apply() method for function
    objects - the following fails:

    function foo() {
    alert( this.length );
    }
    foo.apply( [] );

    Is there a convenient way to add an apply() method to foo that would
    allow this code to work as written?

    --
    Christopher Benson-Manica | I *should* know what I'm talking about - if I
    ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
  • Douglas Crockford

    #2
    Re: apply() workaround

    Christopher Benson-Manica wrote:
    [color=blue]
    > IE 5.0 apparently does not support the apply() method for function
    > objects - the following fails:
    >
    > function foo() {
    > alert( this.length );
    > }
    > foo.apply( [] );
    >
    > Is there a convenient way to add an apply() method to foo that would
    > allow this code to work as written?[/color]

    if (!isFunction(Fu nction.apply)) {
    Function.method ('apply', function (o, a) {
    var r, x = '____apply';
    if (!isObject(o)) {
    o = {};
    }
    o[x] = this;
    switch ((a && a.length) || 0) {
    case 0:
    r = o[x]();
    break;
    case 1:
    r = o[x](a[0]);
    break;
    case 2:
    r = o[x](a[0], a[1]);
    break;
    case 3:
    r = o[x](a[0], a[1], a[2]);
    break;
    case 4:
    r = o[x](a[0], a[1], a[2], a[3]);
    break;
    case 5:
    r = o[x](a[0], a[1], a[2], a[3], a[4]);
    break;
    case 6:
    r = o[x](a[0], a[1], a[2], a[3], a[4], a[5]);
    break;
    default:
    alert('Too many arguments to apply.');
    }
    delete o[x];
    return r;
    });
    }


    See http://www.crockford.com/javascript/remedial.html

    Comment

    Working...