在JavaScript中传递一般函数作为参数?

时间:2017-06-13 15:33:36

标签: javascript forms parameter-passing

我正在使用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问题!

1 个答案:

答案 0 :(得分:2)

是的,你可以这样做,但是这个功能没有在你的function odeon(){ $data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/10565'); $data = json_decode($data); foreach($data->listings as $listing){ $title = $listing->title; $time = implode(', ', $listing->times); Films::updateOrCreate([ 'title' => $title, '$times' => $time ]); } } 对象中定义,它就像另一个变量一样,只需要调用它!

this