JavaScript 함수를 매개 변수로 전달
"부모"함수에서 실행하거나 사용하지 않고 함수를 매개 변수로 어떻게 전달 eval()
합니까? (안전하지 않다는 것을 읽은 이후로.)
나는 이것을 가지고있다:
addContact(entityId, refreshContactList());
작동하지만 문제는 refreshContactList
함수에서 사용될 때가 아니라 함수가 호출 될 때 발생한다는 것입니다.
을 사용하여 돌아볼 수는 eval()
있지만 읽은 내용에 따르면 모범 사례는 아닙니다. JavaScript에서 함수를 매개 변수로 어떻게 전달할 수 있습니까?
괄호 만 제거하면됩니다.
addContact(entityId, refreshContactList);
그런 다음 먼저 실행하지 않고 함수를 전달합니다.
다음은 예입니다.
function addContact(id, refreshCallback) {
refreshCallback();
// You can also pass arguments if you need to
// refreshCallback(id);
}
function refreshContactList() {
alert('Hello World');
}
addContact(1, refreshContactList);
함수를 전달하려면 괄호없이 이름으로 참조하면됩니다.
function foo(x) {
alert(x);
}
function bar(func) {
func("Hello World!");
}
//alerts "Hello World!"
bar(foo);
그러나 때로는 인수가 포함 된 함수를 전달하고 싶지만 콜백이 호출 될 때까지 호출하지 않을 수 있습니다. 이렇게하려면 호출 할 때 다음과 같이 익명 함수로 래핑하면됩니다.
function foo(x) {
alert(x);
}
function bar(func) {
func();
}
//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });
원하는 경우 apply 함수를 사용하고 다음과 같이 인수 배열 인 세 번째 매개 변수를 가질 수도 있습니다 .
function eat(food1, food2)
{
alert("I like to eat " + food1 + " and " + food2 );
}
function myFunc(callback, args)
{
//do stuff
//...
//execute callback when finished
callback.apply(this, args);
}
//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]);
예 1 :
funct("z", function (x) { return x; });
function funct(a, foo){
foo(a) // this will return a
}
예 2 :
function foodemo(value){
return 'hello '+value;
}
function funct(a, foo){
alert(foo(a));
}
//call funct
funct('world!',foodemo); //=> 'hello world!'
함수를 매개 변수로 전달하려면 대괄호를 제거하기 만하면됩니다!
function ToBeCalled(){
alert("I was called");
}
function iNeedParameter( paramFunc) {
//it is a good idea to check if the parameter is actually not null
//and that it is a function
if (paramFunc && (typeof paramFunc == "function")) {
paramFunc();
}
}
//this calls iNeedParameter and sends the other function to it
iNeedParameter(ToBeCalled);
그 배후의 아이디어는 함수가 변수와 매우 유사하다는 것입니다. 쓰는 대신
function ToBeCalled() { /* something */ }
당신은 작성하는 것이 좋습니다
var ToBeCalledVariable = function () { /* something */ }
There are minor differences between the two, but anyway - both of them are valid ways to define a function. Now, if you define a function and explicitly assign it to a variable, it seems quite logical, that you can pass it as parameter to another function, and you don't need brackets:
anotherFunction(ToBeCalledVariable);
There is a phrase amongst JavaScript programmers: "Eval is Evil" so try to avoid it at all costs!
In addition to Steve Fenton's answer, you can also pass functions directly.
function addContact(entity, refreshFn) {
refreshFn();
}
function callAddContact() {
addContact("entity", function() { DoThis(); });
}
I chopped all my hair off with that issue. I couldn't make the examples above working, so I ended like :
function foo(blabla){
var func = new Function(blabla);
func();
}
// to call it, I just pass the js function I wanted as a string in the new one...
foo("alert('test')");
And that's working like a charm ... for what I needed at least. Hope it might help some.
I suggest to put the parameters in an array, and then split them up using the .apply()
function. So now we can easily pass a function with lots of parameters and execute it in a simple way.
function addContact(parameters, refreshCallback) {
refreshCallback.apply(this, parameters);
}
function refreshContactList(int, int, string) {
alert(int + int);
console.log(string);
}
addContact([1,2,"str"], refreshContactList); //parameters should be putted in an array
You can also use eval()
to do the same thing.
//A function to call
function needToBeCalled(p1, p2)
{
alert(p1+"="+p2);
}
//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
eval(aFunction + "("+params+")");
}
//A function Call
callAnotherFunction("needToBeCalled", "10,20");
That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.
Here it's another approach :
function a(first,second)
{
return (second)(first);
}
a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world
In fact, seems like a bit complicated, is not.
get method as a parameter:
function JS_method(_callBack) {
_callBack("called");
}
You can give as a parameter method:
JS_method(function (d) {
//Finally this will work.
alert(d)
});
The other answers do an excellent job describing what's going on, but one important "gotcha" is to make sure that whatever you pass through is indeed a reference to a function.
For instance, if you pass through a string instead of a function you'll get an error:
function function1(my_function_parameter){
my_function_parameter();
}
function function2(){
alert('Hello world');
}
function1(function2); //This will work
function1("function2"); //This breaks!
See JsFiddle
Some time when you need to deal with event handler so need to pass event too as an argument , most of the modern library like react, angular might need this.
I need to override OnSubmit function(function from third party library) with some custom validation on reactjs and I passed the function and event both like below
ORIGINALLY
<button className="img-submit" type="button" onClick=
{onSubmit}>Upload Image</button>
MADE A NEW FUNCTION upload
and called passed onSubmit
and event as arguments
<button className="img-submit" type="button" onClick={this.upload.bind(this,event,onSubmit)}>Upload Image</button>
upload(event,fn){
//custom codes are done here
fn(event);
}
You can use a JSON as well to store and send JS functions.
Check the following:
var myJSON =
{
"myFunc1" : function (){
alert("a");
},
"myFunc2" : function (functionParameter){
functionParameter();
}
}
function main(){
myJSON.myFunc2(myJSON.myFunc1);
}
This will print 'a'.
The following has the same effect with the above:
var myFunc1 = function (){
alert('a');
}
var myFunc2 = function (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
Which is also has the same effect with the following:
function myFunc1(){
alert('a');
}
function myFunc2 (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
And a object paradigm using Class as object prototype:
function Class(){
this.myFunc1 = function(msg){
alert(msg);
}
this.myFunc2 = function(callBackParameter){
callBackParameter('message');
}
}
function main(){
var myClass = new Class();
myClass.myFunc2(myClass.myFunc1);
}
참고URL : https://stackoverflow.com/questions/13286233/pass-a-javascript-function-as-parameter
'Nice programing' 카테고리의 다른 글
Django 뷰에서 2 개 이상의 쿼리 셋을 결합하는 방법은 무엇입니까? (0) | 2020.10.02 |
---|---|
MongoDB를 통해 CouchDB를 사용하거나 그 반대의 경우 (0) | 2020.10.02 |
속성 값을 기준으로 JavaScript 개체 정렬 (0) | 2020.10.02 |
자바 스크립트로 오디오를 재생 하시겠습니까? (0) | 2020.10.02 |
모의 메서드가 전달 된 인수를 반환하도록 만들기 (0) | 2020.10.02 |