search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript function recursion, callbacks, closures and scope usage examples

Recursive call (arguments.callee)
Recursive call is to call yourself. Calls are divided into: direct calls and indirect calls. The following shows the use of recursive calls to calculate the Fibonacci sequence of specified values.

// 求i的阶乘
function factorial(i){
    if(i < 2){
        return 1;
    }
    return i*factorial(i-1); // 递归调用
}
alert(factorial(5)); // 求5的阶乘
// 以上方式存在一个问题?如下:
var factorial = function(i){
    if(i < 2){
        return 1;
    }
    return i*factorial(i-1); // factorial还能被调用吗?不能
}
var test = factorial; 
factorial = null;  
alert(test(2));
// 解决方案:
var factorial = function(i){
    if(i < 2){
        return 1;
    }
    return i*arguments.callee(i-1); // arguments.callee返回正被执行的 Function 对象,也就是所指定的 Function 对象的正文
}
var test = factorial;
factorial = null;
alert(test(5));

Scope

// 在程序中,作用域控制着变量的可见性和生命周期。
var name = "default"; // 全局作用域
function getName(){
    var name = "getName"; // getName作用域下
    for(var i=0; i<2; i++){
        var inName = "inName";
    }
alert(i + "," + inName); // 2,inName 注意:在js中没有块级作用域,及if、for、while中声明的变量是放在块所在的作用域下
    return name;
}
alert(getName()); // getName 注意:js存在函数作用域,所以在函数内部定义的变量在外部是不可见的
alert(name); // default

Note: In many modern languages, it is recommended to delay declaration of variables as much as possible. Such as: java, but in js, this is not recommended because js does not support block-level scope. It is recommended to declare all variables used at the beginning of the function.

Closure
The context in which a function can access the environment when it is created is called a closure. The benefit of scope is that the inner function can access all variables of the outer function (except this and arguments).

var myObject = {
    value   : 0,
    increment : function(inc){
        this.value = typeof inc === &#39;number&#39; ? inc : 1;
    },
    getValue  : function(){
        return this.value;
    }
};
myObject.increment(10);
alert(myObject.value);
alert(myObject.getValue());
// 上面使用字面常量方式定义了一个myObject对象。但是value变量可以被外部对象访问
var myObject = function(){
    var value = 0;
    return {
        increment: function(inc){
            value += typeof inc === &#39;number&#39; ? inc : 1;
        },
        getValue : function(){
            return value;
        }
    };
}();
myObject.increment(10);
alert(myObject.value); // 不能被外部对象访问
alert(myObject.getValue()); // 10
// 渐变body的背景色(黄色到白色)
var fade = function(node){
    var level = 1;
    var step = function(){
        var hex = level.toString(16);
        node.style.backgroundColor = &#39;#FFFF&#39; + hex + hex;
        if(level < 15){
            level += 1;
            setTimeout(step, 500); // 如果level小于15,则内部函数自我调用
        }
    };
    setTimeout(step, 1); // 调用内部函数
};
fade(document.body);
// 下面是一个很糟糕的例子
<a href="#" name="test">点击我...</a><br> // 点击时显示3
<a href="#" name="test">点击我...</a><br> // 点击时显示3
<a href="#" name="test">点击我...</a><br> // 点击时显示3
var add_the_handlers = function(nodes){
    var i;
    for(i = 0; i < nodes.length; i += 1) {
        nodes[i].onclick = function(e){ // 函数构造时的:i
            alert(i);
        };
    }
};
var objs = document.getElementsByName("test");
add_the_handlers(objs);
// 造成上面的原因是:a标签的事件函数绑定了变量i,则不是函数在构造时的i值。
// 解决方案如下:
var add_the_handlers = function(nodes){
    var i;
    for(i = 0; i < nodes.length; i += 1) {
        nodes[i].onclick = function(i){
            return function(e){
                alert(i); // 输出的i是构造函数传递进来的i,不是事件处理绑定的i。
            };
        }(i);
    }
};
var objs = document.getElementsByName("test");
add_the_handlers(objs);

Callbacks

// data表示参数,而call_function则表示回调函数
function sendRequest(data, call_function){
    // setTimeout来模仿客户端请求服务端中传输数据的时间。
    // 当3秒钟后就调用回调函数(有客户端实现回调函数)
    setTimeout(function(){
        call_function(data); // 调用回调函数
    }, 3000);
}
// 测试sendRequest函数
sendRequest("参数", function(context){
    alert("context=" + context);
});

The above is the detailed content of Detailed explanation of JavaScript function recursion, callbacks, closures and scope usage examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft