[英]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.