[英]How to call a function only once for a specific argument in JavaScript?
I have a simple function with two arguments.我有一个简单的 function 和两个 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");
我希望当我们用 arguments 调用这个 function 时,比如 - addError(elem_1, "Error message");
. . This function should not call again with the same first argument(elem_1) .此 function 不应使用相同的第一个参数(elem_1)再次调用。 It can be called with the different arguments but can not be called with the same first argument(elem_1) .它可以用不同的 arguments 调用,但不能用相同的第一个参数(elem_1)调用。 How can I do this?我怎样才能做到这一点?
You can use a WeakSet
to store the first arguments the function has been invoked with.您可以使用WeakSet
存储第一个 arguments function 已被调用。
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.