[英]Strict-Mode: Alternative to argument.callee.length?
Javascript:權威指南 (2011) 有這個示例 (p.186),它在嚴格模式下不起作用,但沒有說明如何在嚴格模式下實現它——我能想到要嘗試的事情,但想知道最佳實踐/security/performance——在嚴格模式下做這種事情的最好方法是什么? 這是代碼:
// 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.
}
您可以只傳遞您正在檢查的 function。
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 返回一個 function 將自動進行檢查......
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;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.