简体   繁体   English

Javascript函数执行顺序

[英]Javascript function execution order

I am new to javascript and have a quick question. 我是javascript的新手并且有一个简单的问题。 Say i have the following code: 说我有以下代码:

function entryPoint()
{
   callFunction(parameter);
}

function callFunction(parameter)
{
   ... //do something here
   var anotherFunction = function () { isRun(true); };
}

My question is that when callFunction(parameter) is called, and the variable anotherFunction is declared, does isRun(true) actually execute during this instantiation? 我的问题是,当callFunction(parameter)并声明变量anotherFunctionisRun(true)在此实例化期间实际执行? I am thinking it doesnt and the contents of the anotherFunction are only "stored" in the variable to be actually executed line by line when, somewhere down the line, the call anotherFunction() is made. 我认为它没有,并且anotherFunction的内容只是“存储”在变量中,以便在行的某个地方逐行执行调用anotherFunction() Can anyone please clarify the function confusion? 任何人都可以澄清功能混乱吗?

It seems the confusion is this line of code 似乎混淆了这行代码

var anotherFunction = function () { isRun(true); };

This declares a variable of a function / lambda type. 这声明了一个函数/ lambda类型的变量。 The lambda is declared it is not run. lambda声明它没有运行。 The code inside of it will not execute until you invoke it via the variable 在您通过变量调用它之前,它内部的代码将不会执行

anotherFunction(); // Now it runs

You almost described it perfectly. 你几乎完美地描述了它。

anotherFunction just receives a reference to a newly created Function Object (yes, Functions are also Objects in this language) but it does not get executed. anotherFunction只接收对新创建的Function Object的引用(是的,函数也是这种语言的对象),但它不会被执行。

You could execute it by calling 你可以通过调用来执行它

anotherFunction();

for instance. 例如。

You can write a simple test like so: 您可以编写一个简单的测试:

entryPoint();

function entryPoint()
{
    alert("In entryPoint");
    callFunction();
}

function callFunction()
{
    alert("In callFunction");
    var anotherFunction = function () { isRun(); };
}

function isRun()
{
    alert("In isRun");
}

​ And, the answer is no, isRun() does not get called. 答案是否定的,isRun()不会被调用。

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

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