2012-04-08 16 views
5

Javascript: The Definitive Guide (2011) ha questo esempio (p.186) che non funziona in modalità rigorosa ma non mostra come implementarlo in modalità rigorosa - Posso pensare a cose da provare ma mi sto chiedendo best practice/sicurezza/prestazioni - qual è il modo migliore per fare questo genere di cose in modalità rigorosa? Ecco il codice:Modalità rigorosa: alternativa a argument.callee.length?

// This function uses arguments.callee, so it won't work in strict mode. 
function check(args) { 
    var actual = args.length;   // The actual number of arguments 
    var expected = args.callee.length; // The expected number of arguments 
    if (actual !== expected)   // Throw an exception if they differ. 
     throw Error("Expected " + expected + "args; got " + actual); 
} 

function f(x, y, z) { 
    check(arguments); // Check that the actual # of args matches expected #. 
    return x + y + z; // Now do the rest of the function normally. 
} 

risposta

3

Si potrebbe semplicemente passare la funzione che si sta controllando.

function check(args, func) { 
    var actual = args.length, 
     expected = func.length; 
    if (actual !== expected) 
     throw Error("Expected " + expected + "args; got " + actual); 
} 

function f(x, y, z) { 
    check(arguments, f); 
    return x + y + z; 
} 

o estendere Function.prototype se ti trovi in ​​un ambiente che gli permetterà ...

Function.prototype.check = function (args) { 
    var actual = args.length, 
     expected = this.length; 
    if (actual !== expected) 
     throw Error("Expected " + expected + "args; got " + actual); 
} 

function f(x, y, z) { 
    f.check(arguments); 
    return x + y + z; 
} 

Oppure si potrebbe fare una funzione di decoratore che restituisce una funzione che fare il controllo automaticamente ...

function enforce_arg_length(_func) { 
    var expected = _func.length; 
    return function() { 
     var actual = arguments.length; 
     if (actual !== expected) 
      throw Error("Expected " + expected + "args; got " + actual); 
     return _func.apply(this, arguments); 
    }; 
} 

... e usarlo come questo ...

var f = enforce_arg_length(function(x, y, z) { 
    return x + y + z; 
}); 
+5

perché comunità wiki tutto – Raynos

+1

@Raynos: Basta che non preoccupa SO punti rep credo. Rende la risposta più invitante per gli altri che vogliono contribuire. –

Problemi correlati