6

Javascript: The Definitive Guide (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 に答える