2013-12-19 1 views
2

나는 함수 호출시 함수의 매개 변수로로드 될 다양한 수의 인수를 전달할 수있는 방법을 알고 있습니다 (call()). 내가 뭔가를 할 수있는 노력을 어디에 내가 반복 된 집합 객체를 통해 RaphaelJS에서 forEach (jQuery의 each과 유사)을 반복하는지, 자식 요소가 다른 집합인지 여부를 결정하고, 그렇지 않은 경우 변수 개수가있는 함수를 적용합니다. 모든 함수를 적용 할 수 있도록 범용으로 만들고 싶지만 함수의 arguments 속성에 액세스하지 않고도 전달하는 함수에 간단한 매개 변수 생성자가 있어야합니다.JavaScript에서 다양한 수의 인수를 사용하여 함수를 호출하십시오 (call()과 유사 함)

function recursiveFncApply(set, fnc, args) { 
    set.forEach(function(item) { 
     if (item.type == 'set') { 
      recurseApplyFncToSets(item, fnc, args); 
     } else { 
      fnc(item, args); 
     } 
    }); 
} 

function translateOperation(element, operation, x, y) 
    // do stuff to element with operation, x, and y args without accessing 
    // accessing arguments property 
} 

recursiveFncApply(passedSet, translateOperation, [arg1, [arg2, ...]]); 

은 내가 인수를 결정하는 코드로 자신을 반복 할 필요없이 여러 기능을 사용할 수 있도록이 작업을 수행 할 수 제대로 사용하기 전에 할당합니다. 어떤 종류의 기능이나 언어 유틸리티가 있는지 모르겠습니다. 필자는이 작업을 수행 할 수 없거나 recursiveFncApply에 전달 된 나머지 인수에서 함수 호출을 프로그래밍 방식으로 "생성"할 수 있습니다. JavaScript로 가능합니까?

설명 : 반복되는 함수에 가변 개수의 인수를 전달하여 재귀 함수가 작업중인 집합의 내용에 적용 할 함수에 전달할 함수에 전달하려고합니다. 그래서 recursiveFncApply 함수를 call()을 통해 실행되는 함수처럼 작동하는 인수 구조를 사용하면서 일반적으로 모든 함수로 작업 할 수 있기를 원합니다.

recursiveFncApply(passedSet, translateOperation, operation, x, y); 
recursiveFncApply(passedSet, anotherFunction, singleArg); 

뿐만 아니라이 방법 :

recursiveFncApply(passedSet, anotherFunction, singleArg); 

function anotherFunction(element, differentArg) { 
    // do something with one argument 
} 

가 이상적으로는 다음이 방법으로 내 recursiveFncApply을 사용할 수

내가 translateOperation 이외에 다른 기능을 말해봐

이 방법이 비슷하다고 생각합니다. call() wo 점에서 RKS 내가 할 수 :

anotherFunction.call(this, element, differentArg); 

있습니다 .. arguments 속성을 제압 anotherFunction의 구조를 변경하거나, 객체/배열을 전달하지 않고.

+0

의 중복 가능성 http://stackoverflow.com/questions/2141520/javascript-variable-number- of-arguments-to-function –

+1

인수 대신에 { 'a': 'something', 'b': 'something else'}를 전달하십시오. –

+0

어쩌면 내가 당신의 문제를 오해하지만, 인수 배열을 사용하고 ['fnc.apply'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/)를 사용하는 것을 고려해 보았습니까? 기능/적용)? – apsillers

답변

0

펠릭스 킹 (Felix King)이 올바른 아이디어를 갖고 있다는 것이 밝혀졌습니다. 나는 함수에서 함수로의 전달 인자 (대답 : here 발견)가 실제로 무엇을하려고 하는지를 깨닫 자마자 나의 질문에 대한 직접적인 답을 찾았다. 그렇지 않으면 내가 충돌, 나는 다음 재귀 루프 앞으로 통과하기 전에 arguments에서 set 속성을 업데이트해야하기 때문에

function recursiveSetFncApply(set, fnc/*, variable */) { 
    var me = this; 
    var parentArgs = arguments; 
    set.forEach(function(element) { 
     if (element.type == 'set') { 
      parentArgs[0] = element; 
      me._recursiveSetFncApply.apply(me, parentArgs); 
     } else { 
      // Generate args from optional arguments and pass forward; put element in args at front 
      var args = Array.prototype.slice.call(parentArgs, 2); 
      args.unshift(element); 
      fnc.apply(element, args); 
     } 
    }); 
} 

내가 parentArgsarguments에 대한 참조를 만들 : 그래서는이 코드와 함께 작동하도록 있어요 무한 루프는 원래의 인수 세트를 사용하기 때문에 전혀 업데이트되지 않았기 때문에 루프를 종료합니다. 나는 apply()이 실제로 전달 인자를 전달하지 않을 것이라는 인상을 받았지만, 단순히 인덱스로 접근해야만하는 새로운 함수에 배열을 추가합니다. 이것은 사실이 아닙니다. apply()translateElementOperation에 올렸을 때 정확한 위치에 필요한 모든 인수가있었습니다.다음은 재귀 적용을 통해 실행 된 업데이트 된 함수입니다.

function translateElementOperation(element, operation, x, y) { 
    var currentPath = element.attr('path'); 
    translatedPath = Raphael.transformPath(currentPath, [operation, x, y]); 
    element.attr('path', translatedPath); 
} 

도움을 주셔서 감사합니다.

0

사용 .apply 대신 .call

functionName.apply(element, [any, number, of, variables, ...]); 

// instead of this 
functionName.apply(element, set, of, variables, ...); 

의이과 같이 더 유용

var fnVars = [];// fill this anyway you want. 

functionName.apply(element, fnVars); 
관련 문제