关闭JavaScript - 什么错? [英] Closure in JavaScript - whats wrong?

查看:113
本文介绍了关闭JavaScript - 什么错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用闭包:

function func(number) {
    var result = number;

    var res = function(num) {
        return result + num;
    };
    return res;
}

var result = func(2)(3)(4)(5)(3);
console.log(result); // 17

我需要接收2 + 3 + 4 + 5 + 3 = 17
但是我得到一个错误:Uncaught TypeError:number不是一个函数

I need to receive 2 + 3 + 4 + 5 + 3 = 17 But I got an error: Uncaught TypeError: number is not a function

推荐答案

,在那里你将返回结果数字而不是另一个函数。您可以选择:

You somehow have to signalize the end of the chain, where you are going to return the result number instead of another function. You have the choice:


  • 使函数返回一个固定的次数 - 这是使用语法的唯一方法有它,但它无聊。看看@PaulS的答案。您可以进行第一次调用( func(n))提供 sum curried

  • 在某些情况下返回结果,例如调用函数时没有参数(@PaulS的第二个实现)或一个特殊的值( null in @ AmoghTalpallikar的回答)。

  • 对返回值的函数对象。 valueOf()非常适合,因为当函数被强制转换为原始值时,它将被调用。看到它在行动:

  • make it return a function for a fixed number of times - this is the only way to use the syntax like you have it, but it's boring. Look at @PaulS' answer for that. You might make the first invocation (func(n)) provide the number for how many arguments sum is curried.
  • return the result under certain circumstances, like when the function is called with no arguments (@PaulS' second implementation) or with a special value (null in @AmoghTalpallikar's answer).
  • create a method on the function object that returns the value. valueOf() is suited well because it will be invoked when the function is casted to a primitive value. See it in action:

function func(x) {
    function ret(y) {
        return func(x+y);
    }
    ret.valueOf = function() {
        return x;
    };
    return ret;
}

func(2) // Function
func(2).valueOf() // 2
func(2)(3) // Function
func(2)(3).valueOf() // 5
func(2)(3)(4)(5)(3) // Function
func(2)(3)(4)(5)(3)+0 // 17


这篇关于关闭JavaScript - 什么错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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