Strict-Mode:argument.callee.length的替代方法

Strict-Mode: Alternative to argument.callee.length?

本文关键字:方法 length argument callee Strict-Mode      更新时间:2023-09-26

Javascript: The Definitive Guide (2011) 有这个例子(p.186),它在严格模式下不起作用,但没有展示如何在严格模式下实现它 - 我可以想到要尝试的事情,但我想知道最佳实践/安全性/性能 - 在严格模式下做这种事情的最佳方法是什么? 代码如下:

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