2012-04-08 56 views
5

Javascript:權威指南(2011)有這個例子(第186頁),它不能在嚴格模式下工作,但沒有說明如何在嚴格模式下實現它 - 我可以考慮要嘗試的東西,但我想知道最佳實踐/安全/性能 - 在嚴格模式下做這種事情的最佳方式是什麼?這裏的代碼:Strict-Mode:替代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. 
} 

回答

3

你可以只傳遞你檢查的函數。

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; 
} 

或延長Function.prototype,如果你的環境中,將允許它是......

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; 
} 

或者你可以做一個返回函數,將一個裝飾功能自動檢查...

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); 
    }; 
} 

...並使用它像這樣...

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

爲什麼社區維基一切 – Raynos 2012-04-08 23:46:26

+1

@Raynos:只是不關心SO代表處點我猜。使答案更吸引其他想要貢獻的人。 – 2012-04-08 23:49:56