


Detailed 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 === 'number' ? 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 === 'number' ? 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 = '#FFFF' + 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

Variable expected value exceptions in Java can be solved by: initializing variables; using default values; using null values; using checks and assignments; and knowing the scope of local variables.

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.

Can. C++ allows nested function definitions and calls. External functions can define built-in functions, and internal functions can be called directly within the scope. Nested functions enhance encapsulation, reusability, and scope control. However, internal functions cannot directly access local variables of external functions, and the return value type must be consistent with the external function declaration. Internal functions cannot be self-recursive.

In Vue, there is a difference in scope when declaring variables between let and var: Scope: var has global scope and let has block-level scope. Block-level scope: var does not create a block-level scope, let creates a block-level scope. Redeclaration: var allows redeclaration of variables in the same scope, let does not.

In JavaScript, the pointing types of this include: 1. Global object; 2. Function call; 3. Constructor call; 4. Event handler; 5. Arrow function (inheriting outer this). Additionally, you can explicitly set what this points to using the bind(), call(), and apply() methods.
