martes, 2 de julio de 2013

Soporte "call" y "apply" para navegadores antiguos

Call:

//------------------------------------------------------------------------------------------------
// Engines      JavaScript 1.1+
//              JScript    2+
// Environments NN3+ IE4+ MOZILLA1+ SAFARI1+
//------------------------------------------------------------------------------------------------
function __fn_call (o /* object, arg1 [, ... [, argN]] */)
{
    var a = arguments;
    var s = '';
    var u;

    for (var i = 1, l = a.length, n = l - 1; i < l; ++i)
    {
        s += 'a[' + i + ']';
  
        if (i < n) 
            s+= ',';
    }
 
    if (o == null)
        s = eval('this(' + s + ')');
  
    else
    {
        o.__callback = this;
        s = eval('o.__callback(' + s + ')');
        o.__callback = u;
    }
 
    return s;
}

//------------------------------------------------------------------------------------------------

if (!Function.prototype.call) Function.prototype.call = __fn_call;

Apply:

//------------------------------------------------------------------------------------------------
// Engines      JavaScript 1.1+
//              JScript    2+
// Environments NN3+ IE4+ MOZILLA1+ SAFARI1+
//------------------------------------------------------------------------------------------------
function __fn_apply (o /* object */, a /* [args] */ )
{
    var u, s = '';
    if (a && a.constructor == Array) for (var i = 0, l = a.length, n = l - 1; i < l; ++i)
    {
        s += 'a[' + i + ']';
  
        if (i < n)
            s+= ',';
    }
 
    if (o == null)
        s = eval('this(' + s + ')');
  
    else
    {
        o.__callback = this;
        s = eval('o.__callback(' + s + ')');
        o.__callback = u;
    }
 
    return s;
}

//------------------------------------------------------------------------------------------------

if (!Function.prototype.apply) Function.prototype.apply = __fn_apply;

No hay comentarios:

Publicar un comentario