Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I copy/clone a function in JavaScript?
    text
    copied!<p>I'm using jQuery with the validators plugin. I would like to replace the "required" validator with one of my own. This is easy:</p> <pre><code>jQuery.validator.addMethod("required", function(value, element, param) { return myRequired(value, element, param); }, jQuery.validator.messages.required); </code></pre> <p>So far, so good. This works just fine. But what I <em>really</em> want to do is call my function in some cases, and the default validator for the rest. Unfortunately, this turns out to be recursive:</p> <pre><code>jQuery.validator.addMethod("required", function(value, element, param) { // handle comboboxes with empty guids if (someTest(element)) { return myRequired(value, element, param); } return jQuery.validator.methods.required(value, element, param); }, jQuery.validator.messages.required); </code></pre> <p>I looked at the source code for the validators, and the default implementation of "required" is defined as an anonymous method at jQuery.validator.messages.required. So there is no other (non-anonymous) reference to the function that I can use.</p> <p>Storing a reference to the function externally before calling addMethod and calling the default validator via that reference makes no difference.</p> <p>What I really need to do is to be able to copy the default required validator function by value instead of by reference. But after quite a bit of searching, I can't figure out how to do that. Is it possible?</p> <p>If it's impossible, then I can copy the source for the original function. But that creates a maintenance problem, and I would rather not do that unless there is no "better way."</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload