何时使用带有javascript函数的括号 [英] When to use parentheses with javascript function

查看:77
本文介绍了何时使用带有javascript函数的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 showText()的函数,它将表单文本框中的一些文本复制到其他地方的段落。使用以下方法调用它:

I have a function called showText() which copies some text from form textbox to a paragraph elsewhere. It is called with the following:

document.getElementById("mybutton").onclick = showText; 

如果我将()添加到showText的末尾,它将无效,我从阅读中理解这里类似的答案是调用函数的唯一方法。

It will not work if I add the () to the end of showText, which I understand from reading similar answers here is the only way to call a function.

稍后在脚本中它需要()工作:

Later in the script it requires the () to work:

window.addEventListener("keypress", function(e) {
    var keycode = e.keyCode;
    if (keycode == 13) {
        showText();
    }
}, false);

我不确定这里发生了什么。

I'm not sure what is going on here.

推荐答案

showText 返回函数 showText

showText()运行函数 showText 并返回结果

将函数附加到.onclick等事件处理程序时,它需要 function

When you attach a function to an event handler like .onclick, it is expecting a function.

您可以调用函数并将结果返回到如下事件: document.getElementById (mybutton)。onclick = showText(); 提供函数本身返回函数:

You can call a function and return the result to an event like this: document.getElementById("mybutton").onclick = showText(); provided the function itself returns a function:

function showText() {
    return function () { 
        alert('hello world'); 
    }
}

这篇关于何时使用带有javascript函数的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆