简体   繁体   中英

javascript - passing a function within itself

I have a JavaScript function which is called "updateData" that I am passing as a parameter to another function "process" within the function "updateData" itself.

var updateData = function(){
  var bean= {
    "name" : $("#name").val(),
    "sort" : $('#sort').val(),
    "reference" : "sample" 
  };
  var param = {
    'bean' : bean,
    'reference' : "sample" ,
    'ajaxtype' : 'POST',
    'url' : 'samp.json',
    'valFn' : validateData,
    'updateFn' : updateData,
    'populateFn' : populateData
  };
  process(param );
};

I'm doing this because I need to bind the function "updateData" to a button that is created in process().

Will this cause any problems? Is it correct?

(I have not faced any issues till now. But I am new to functional programming, and I wanted to be sure that doing this will not cause any problems).

This will work. Reason for this to work is that function is just defined and not evaluated at the time of writing this function. So, by the time you call this function, updateData variable already has a reference to function object and that reference will be passed to the object that you have defined inside.

Yes you can. A function can refer to itself inside its definition. Because without that you will not be able to make recursive calls.

Since the below code can work:

var updateData= function() {
    if(someCondition){
        updateData();
    } else {
        return;
    }
}

The following code will also work:

var updateData= function() {
    process(updateData);
}

OR

var updateData= function() {
    var param = {'updateFn' : updateData};
    process(param);
}

Your code will work absolutely fine. Just be sure it doesn't go into an infinite loop.

It would work.

var upDateData = function() {
  var params = { data : upDateData };
  alert(params.data);
}

upDateData();

But then you can use delegation to handle that, if the button is getting rendered in the same page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM