2012-04-08 7 views
5

Javascript : The Definitive Guide (2011)에는 엄격 모드에서는 작동하지 않지만 엄격 모드로 구현하는 방법은 나와 있지 않은이 예제가 있습니다. (p.186) - 시도 할 생각이 있지만 궁금합니다. 베스트 프랙티스/보안/성능 - 엄격 모드에서 이러한 일을하는 가장 좋은 방법은 무엇입니까? 코드는 다음과 같습니다.엄격 모드 : argument.callee.length의 대안?

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

답변

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; 
}); 
+5

왜 커뮤니티 위키의 모든 – Raynos

+1

@Raynos : 같아요 SO 대표 지점에 대한 그냥 관심이 없습니다. 기부를 원하는 다른 사람들에게 답변을 더 많이 초청합니다. –