6

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.
}
4

1 回答 1

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;
});
于 2012-04-08T23:41:32.817 回答