简体   繁体   English

javascript中的函数 - 定义和调用它们,有或没有函数名称

[英]functions in javascript - defining and calling them, with or without a function name

My question is easiest explained with the code block and the questions below it. 我的问题最容易解释为代码块和它下面的问题。

But here is an attempt to explain my question in English: 但这是试图用英语解释我的问题:

I am learning JavaScript (and I am lazy so I use a lot of jQuery... ;) ) and I came across something which I don't quite understand, and I don't know what it is called, therefore I don't know what terms i should research. 我正在学习JavaScript(而且我很懒,所以我使用了很多jQuery ...;))我遇到了一些我不太了解的东西,而且我不知道它叫什么,因此我不知道我知道应该研究什么术语。

Basically I am wondering when it is necessary to use function(){ ... } (without a name) and when to use function function_name(){ ... } (with a name), and how to execute a function with things like .click() .post() or setTimeout() . 基本上我想知道何时需要使用function(){ ... } (没有名称)以及何时使用function function_name(){ ... } (带名称),以及如何使用函数执行函数像.click() .post()setTimeout()

I know a couple of jQuery functions, like .click() that require you to put in a function to be called. 我知道一些jQuery函数,比如.click() ,它们要求你输入一个要调用的函数。 But the thing is, you can't just say .click( function_name() ) (this would call the function immediately upon executing the script if I interpreted my test results correctly) instead you have to do .click( function(){ ... }) or you can do .click( function function_name(){ ... }) . 但问题是,你不能只说.click( function_name() ) (如果我正确地解释了我的测试结果,这将在执行脚本时立即调用该函数)而不是你必须做.click( function(){ ... })或者你可以做.click( function function_name(){ ... }) I also found out that you can say .click( function_name ) as long as you define beforehand var function_name = function function_name(){ ... } whereas the function name is optional, it will work with or without adding that. 我还发现只要事先定义var function_name = function function_name(){ ... }就可以说.click( function_name ) ,而函数名是可选的,无论是否添加它都可以。

I made an example with all possible scenarios I could think of. 我举了一个例子,说明了我能想到的所有可能情况。 And I did find out what is working and what isn't, now I want to find out why each one is working and others aren't. 我确实找到了什么工作,什么不工作,现在我想找出为什么每个人都在工作而其他人没有工作。

I am hoping understanding this will help me better understand asynchronous functions such as .post() or setTimeout() . 我希望理解这将有助于我更好地理解异步函数,如.post()setTimeout()

<button id="one">Button 1</button>
<button id="two">Button 2</button>
<button id="three">Button 3</button>
<button id="four">Button 4</button>
<button id="five">Button 5</button>
<button id="six">Button 6</button>
<button id="seven">Button 7</button>
<button id="eight">Button 8</button>
<button id="nine">Button 9</button>

<script type="text/javascript">
    function alert_three(){
        alert('three');
    }

    var alert_four = function(){
        alert('four');
    }

    function alert_five(){
        alert('five');
    }

    var alert_five = alert_five();
    //this will alert five right away, because we call to the function alert five, which does not return anything but creates an alert box.

    var alert_six = function alert_six(){
        alert('six');
    }

    $('#one').click( function(){
        alert('one');
    });
    //this will work correctly.

    $('#two').click( alert('two') );
    //this will alert two right away, because...?
    //it wont do anything else on click

    $('#three').click( alert_three() );
    //this will alert three right away, because...?
    //it wont do anything else on click

    $('#four').click( alert_four );
    //this will work correctly.

    $('#five').click( alert_five );
    //this wont do anything else on click

    $('#six').click( alert_six );
    //this will work correctly.

    $('#seven').click( function alert_seven(){
        alert('seven');
    });
    //this will work correctly.

    function alert_eight(){
        return function(){
           alert('eight');
        }
    }

    $('#eight').click( alert_eight() );
    //this will work correctly      

    function alert_nine(){
       alert('nine');
    }

    $('#nine').click( alert_nine ); 
    //this will not work
</script>
  • Why will this script alert first five, then two, then three on startup? 为什么这个脚本会在启动时提前五个,然后两个,然后三个提醒?
  • Why will only buttons 1, 4, 6, and 7 work correcty? 为什么只有按钮1,4,6和7才能正常工作?
  • How would you describe the differences between the working buttons? 您如何描述工作按钮之间的差异?
  • Which variation would you use when and why? 您何时以及为何使用哪种变体? (meaning: when to give it a name, when to write the function in a variable?) (意思是:何时给它起一个名字,何时在变量中写入函数?)

A Fiddle for the same: http://jsfiddle.net/ZfnaM/5/ 同样的小提琴: http//jsfiddle.net/ZfnaM/5/

Basically I am wondering when it is necessary to use function(){ ... } (without a name) and when to use function function_name(){ ... } (with a name) 基本上我想知道何时需要使用function(){ ... } (没有名称)以及何时使用函数function_name(){ ... } (带名称)

It is never really necessary to use either. 从来没有必要使用它们。 It is just sometimes more convenient to use one or the other. 使用其中一种或另一种有时更方便。

and how to execute a function with things like .click() .post() or setTimeout(). 以及如何使用.click()。post()或setTimeout()等函数执行函数。

If you are using the function that accepts the callback, then you just pass the function you want to use as the callback like any other variable or literal. 如果您正在使用接受回调的函数,那么您只需将要用作回调的函数传递给任何其他变量或文字。

If you want to write a function that uses a callback, then it essentially boils down to: 如果你想编写一个使用回调的函数,那么它基本上归结为:

function accepts_callback(callback) {
    callback();
}
function a_callback() {
    alert("This is a callback");
}
accepts_callback(a_callback);

you can't just say .click( function_name() ) 你不能只说.click( function_name() )

Putting () after a function will call it. 在函数之后放置()将调用它。 Don't include them as you can pass it. 不要包括它们,因为你可以通过它。

Why will this script alert first five, 为什么这个脚本会提前五个警告,

The first thing you do, other then declare functions, is make a function call: var alert_five = alert_five(); 你做的第一件事,然后是声明函数,就是进行函数调用: var alert_five = alert_five();

then two 然后两个

$('#two').click( alert('two') ); //this will alert two right away, because...?

You are calling alert here 你在这里叫alert

//it wont do anything else on click //它在点击时不会做任何其他事情

The return value of alert will always be undefined , which isn't a function alert的返回值始终是undefined ,这不是一个函数

then three on startup? 启动时有三个?

$('#three').click( alert_three() ); //this will alert three right away, because...? //这会马上警告三个,因为......?

You are calling the alert_three function immediately. 您正在立即调用alert_three函数。

//it wont do anything else on click //它在点击时不会做任何其他事情

alert_three has no return statement, so it returns undefined , which isn't a function alert_three没有return语句,所以它返回undefined ,这不是一个函数

Why will only buttons 1, 4, 6, and 7 work correcty? 为什么只有按钮1,4,6和7才能正常工作?

The are the only ones for which you give a function as the argument to click() . 这是您将函数作为click()的参数的唯一函数。

What your questions pertain to are called anonymous functions and named functions. 您的问题涉及的是匿名函数和命名函数。 For instance, alert_three is a named function while alert_four (even though you've assigned it to a variable) is an anonymous function. 例如, alert_three是一个命名函数,而alert_four (即使你已将它分配给一个变量)是一个匿名函数。 These functions are interchangeable and the use of one or the other probably won't matter to you until you start doing things like recursion , where you can call a function within itself (and thus it must be named ). 这些函数是可以互换的,在你开始做递归之类的事情之前,使用其中一个函数可能对你没有关系,你可以在其中调用一个函数(因此它必须被命名 )。

In the jQuery examples, the functions are actually callbacks and within the jQuery methods, they are supposed to follow the arguments , which you have replaced several times with direct function calls. 在jQuery示例中,函数实际上是回调 ,在jQuery方法中,它们应该遵循参数 ,您已经使用直接函数调用替换了几次。 Callbacks give you the ability to act upon the context of the function, usually referred to as this . 回调使您能够根据函数的上下文进行操作,通常称为this函数。

When you are using jQuery's .click() you are binding an event handler -- that is the missing vocabulary you seek. 当你使用jQuery的.click()时,你绑定了一个事件处理程序 - 这是你寻找的缺失词汇。

In binding an event handler, you need to pass a function for it work as you are intending. 在绑定事件处理程序时,您需要传递一个函数,因为它可以按照您的意图工作。 For the items that are alerting right away on page load (five, two and three), that is because you aren't providing a function, just a statement or something that evaluates to a statement instead of a function, so it executes right away and doesn't bind a function definition (which is why when you click the button after page load for those you don't get another alert). 对于在页面加载时立即发出警报的项目(五,二和三),这是因为你没有提供一个函数,只是一个语句或者一个评估语句而不是函数的东西,所以它立即执行并且不绑定函数定义(这就是为什么当您在页面加载后单击按钮而没有获得另一个警报时)。

This is what two, three and five have in common -- they aren't (or don't equate to) function definitions, just statements, so they execute when jQuery evaluates the statements on loading the page as it is attempting to add the appropriate functions as event handlers. 这是两个,三个和五个共同点 - 它们不是(或不等于)函数定义,只是语句,因此它们在jQuery在加载页面时评估语句时执行,因为它试图添加适当的函数作为事件处理程序。 This includes five, as you are calling a defined function, rather than passing the function definition. 这包括五个,因为您正在调用已定义的函数,而不是传递函数定义。 You can see in the jQuery documentation for click that you need you pass in a function definition. 您可以在jQuery文档中看到您需要传递的函数定义中的click

This explains the first three questions you were trying to understand. 这解释了您试图理解的前三个问题。

In regard to the last item, that one is more of an opinion. 关于最后一个项目,那个是更多的意见。 I'd use a variable for function definitions that I'd want to bind to multiple events to improve maintenance. 我将一个变量用于函数定义,我希望将其绑定到多个事件以改进维护。

Happy scripting! 快乐的脚本!

Clicking alert_five will not work since you have overwritten the function with a variable. 单击alert_five将不起作用,因为您已使用变量覆盖该函数。

notice that: 注意:

 function alert_five(){
            alert('five');
    }
console.log(alert_five)  
//prints
function alert_five(){
        alert('five');
    }

You then assign alert_five to something else, the returned value of return_five() the function and since it doesn't return anything it is undefined. 然后将alert_five分配给其他东西,返回值return_five()函数,因为它不返回任何未定义的东西。

var alert_five = alert_five();
console.log(alert_five)  
    //prints
undefined

Between bracktes you pass value so when you call function .click(function_name()) you call the function and pass the value that is returned by it. 在括号之间传递值,所以当你调用函数.click(function_name())你调用函数并传递它返回的值。

Some functions take other function as parameter so you have to pass them as function_name 某些函数将其他函数作为参数,因此您必须将它们作为function_name传递

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM