简体   繁体   中英

Changing the definition of a JavaScript function

Suppose you have a function as follows:

function chk() {
    var valid = true;
    if(document.getElementById("bob")) {
        if(document.getElementById("bob").value == "") {
            valid = false;
            writeErrorMessage("bob", "Field 'Bob' is mandatory");
        }
    }
    ... //There may be a lot more than just this field, depending on the clients configuration.
    return valid;
}

This function is output by the core code. Now a client comes along and says they want field 'x' to be made mandatory. On looking through the core code we can see that this field cannot be made mandatory by default, however what we have done previously is something like the following:

var chk2 = chk;
chk = function() {
    var valid = true;
    if(document.getElementById("x")) {
        if(document.getElementById("x").value == "") {
            valid = false;
            writeErrorMessage("x", "Field 'x' is mandatory");
        }
    }
    if(valid) valid = chk2();
    return valid;
}

The problem here is that if valid is false then it won't run the original chk function (chk2) so the error messages for those fields originally validated will not be showing.

What I'd like to do is basically edit the workings of this chk function - add a few lines before the last line, the return valid , so it validates more fields. The problem is that this entire function is output by the core code so, besides the error messages and what fields are validated, this is out of our control. If a field is not able to be made mandatory by default then it will never output this validation code for that field.

Bearing in mind the return valid line is guaranteed to always be there, does anyone know of a way I can take the body of a function, replace a particular part of it and then set the new string as the new body of that function? It seems like something which should be possible with JS but I just can't put my finger on a way to achieve this.

Thanks in advance. Regards, Richard

Having re-read your original question how about this:

//store the original
var old_chk=chk;

// create a new version that first runs the original
chk=function(){
    // run the original validation
    var valid=old_chk();       

    //do your additional tests here
    var el=document.getElementById('x');
    if(el &&!el.value){
       valid=false;
       ...
    }    
return valid
}

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