Javascript Memoization解释? [英] Javascript Memoization Explanation?

查看:160
本文介绍了Javascript Memoization解释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从一本书中读取一个例子,有人可以解释当函数本身没有声明任何参数时,函数调用fibonacci如何接受参数'i'吗?

Reading an example from a book, can someone explain how the function call to fibonacci takes in the argument 'i' when the function itself doesn't declare any parameters?

var fibonacci = (function () {
    var memo = [0, 1];
    var fib = function (n) {
        var result = memo[n];
        if (typeof result !== 'number') {
            result = fib(n - 1) + fib(n - 2);
            memo[n] = result;
        }
        return result;
    };
    return fib;
}());

for(var i = 0; i <= 10; i += 1) {
    document.writeln('// ' + i + ': ' + fibonacci(i));
}


推荐答案

你正在创造一个自我执行匿名函数(function(){}()); 在其中返回 fib 函数,该函数需要论点。 var fib = function(n){} ... return fib;

You are creating a self-executing anonymous function (function(){}()); which inside it returns the fib function, which takes an argument. var fib = function(n){} ... return fib;

var fibonacci = (function () { // Self-executing anonymous function
    var memo = [0, 1];         // local variable within anonymous function
    var fib = function (n) {   // actual fib function (takes one argument)
        var result = memo[n];
        if (typeof result !== 'number') {
            result = fib(n - 1) + fib(n - 2);
            memo[n] = result;
        }
        return result;
    };
    return fib; // return fib (fibonacci is now set to the function fib defined above, which takes one argument)
}());

这个系统(从自动执行的匿名函数返回一个函数)允许你定义变量返回函数仍然可以使用的局部作用域,但不是作用域之外的函数。这是一个示例

This system (returning a function from a self-executing anonymous function) allows for you to define variable in a local scope that can still be used by the returned function, but not by functions outside the scope. Here is an example.

这个技术在JavaScript中称为 closure 。在 MDN指南上阅读更多相关信息。

This technique is called closure in JavaScript. Read more about it on the MDN guide.

这篇关于Javascript Memoization解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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