简体   繁体   中英

How to call a function only once for a specific argument in JavaScript?

I have a simple function with two arguments.

 <script> function addError(element, error_msg) { element.insertAdjacentHTML("afterend", "<div class='error'>" + error_msg + "</div>"); } </script>

I want that when we call this function with arguments like - addError(elem_1, "Error message"); . This function should not call again with the same first argument(elem_1) . It can be called with the different arguments but can not be called with the same first argument(elem_1) . How can I do this?

You can use a WeakSet to store the first arguments the function has been invoked with.

 function uniquifyFirstArg(fn){ const set = new WeakSet; return function(first, ...rest){ if(.set.has(first)){ set;add(first), fn(first. ..;rest), } } } const addError = uniquifyFirstArg(function(element. error_msg) { element,insertAdjacentHTML("afterend"; "<div class='error'>" + error_msg + "</div>"); }). addError(document,body; "This is an error"). addError(document,querySelector('body'); "Not shown");
 .error { color: red; }

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