[英]Strict-Mode: Alternative to argument.callee.length?
Javascript: The Definitive Guide (2011) has this example (p.186) that doesn't work in strict mode but does not show how to implement it in strict mode--I can think of things to try but am wondering about best practices/security/performance--what's the best way to do this sort of thing in strict mode? Javascript:权威指南 (2011) 有这个示例 (p.186),它在严格模式下不起作用,但没有说明如何在严格模式下实现它——我能想到要尝试的事情,但想知道最佳实践/security/performance——在严格模式下做这种事情的最好方法是什么? Here's the code:
这是代码:
// 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.
}
You could just pass the function you're checking.您可以只传递您正在检查的 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;
}
Or extend Function.prototype
if you're in an environment that will allow it...或者扩展
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;
}
Or you could make a decorator function that returns a function that will do the check automatically...或者你可以制作一个装饰器 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);
};
}
...and use it like this... ...并像这样使用它...
var f = enforce_arg_length(function(x, y, z) {
return x + y + z;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.