【问题标题】:Passing a general function as arguments in JavaScript?在 JavaScript 中将通用函数作为参数传递?
【发布时间】:2017-11-15 11:44:54
【问题描述】:

我正在 React.js 中制作一个带有验证的表单。有没有办法可以将“通用”函数作为参数传递?我有验证表单中每个输入的函数。例如,如果我有:

updateState(e) {
        if (this.validateEmail(e.target.value) === true) {
            this.setState({[e.target.className]: e.target.value});
            this.setState({errorMsg: 'Valid'});
            document.getElementById(e.target.className).className = "green";
        }
        else if (e.target.value.length === 0) {
            this.setState({errorMsg: 'Empty submission'});
            document.getElementById(e.target.className).className = "red";
        }
        else {
            this.setState({errorMsg: 'Invalid form input'});
            document.getElementById(e.target.className).className = "red";
        }
}

我希望能够传入 validateName、validateEmail、validateAddress 等函数,所以它看起来像这样:

updateState(e, parameterFunction) {
            if (this.parameterFunction(e.target.value) === true) {
                this.setState({[e.target.className]: e.target.value});
                this.setState({errorMsg: 'Valid'});
                document.getElementById(e.target.className).className = "green";
            }
            else if (e.target.value.length === 0) {
                this.setState({errorMsg: 'Empty submission'});
                document.getElementById(e.target.className).className = "red";
            }
            else {
                this.setState({errorMsg: 'Invalid form input'});
                document.getElementById(e.target.className).className = "red";
            }
    }

这可能吗?

谢谢大家,这是我的第一个 StackOverflow 问题!

【问题讨论】:

  • 别想太多。函数是 JavaScript 中的一等实体——只需像传递其他任何东西一样传递它们!
  • @shabs 感谢您的回复。那么,如果我使用 validateEmail 作为参数调用它,上面的示例会起作用吗?
  • 是的,除了 Dloeda 在下面提出的 this 点。他们在下面的答案更适合您的具体示例,因此为了演示,我将提供一些通用的内容:const double = n => n + n;const applyFunction = (n, f) => f(n)applyFunction(1, double)// ==> 2(编辑:是否有更好的方法来格式化代码块在评论中?)

标签: javascript forms parameter-passing


【解决方案1】:

是的,你可以这样做,但是这个函数没有在你的this对象中定义,它就像另一个变量,调用它!

function updateState(e, validateName, validateEmail, validateAddress) {
    var data = e.target.value;

    if (validateName(data.name) && validateEmail(data.mail) && validateAddress(data.address) {
            //Do some stuff
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多