如何在JavaScript中构造无限fun()()()...()()? [英] How can I construct a infinite fun()()()...()() in JavaScript?
问题描述
只是一个奇怪的问题。我想创建一个可以处理无限层的函数? make add(2)(3),add(1)(2)(3)...(10)all works。
Just a curious question. I want to create a function can handle infinite "layer"? make add(2)(3), add(1)(2)(3)...(10) all works.
任何想法?
推荐答案
你可以轻微抓住。返回值必须是您可以强制转换为数字的函数。方法如下:
You can, with a slight catch. The return value must be a function that you can coerce to a number. Here's how:
function add (addend) {
'use strict'
const sum = (this || 0) + addend
const chain = add.bind(sum)
for (const prop of Object.getOwnPropertyNames(Number.prototype)) {
chain[prop] = Number.prototype[prop].bind(sum)
}
return chain
}
console.log(add(1))
console.log(add(1)(2))
console.log(add(1)(2)(3))
// convinced yet?
let four = add(4)
console.log(typeof four, four === 4)
// it's a function, not a number, so coerce to a primitive first
four = Number(four)
console.log(typeof four, four === 4)
add()
是一个包含上下文(<$ c)的函数$ c>此)和所有 Number.prototype
p属性,包括其 Symbol.toPrimitive
属性。在严格模式中,上下文表现得更多很好,允许你将它定义为一个原始值,如数字,而不是默认为窗口
并强制绑定基元到对象
s。
add()
is a function that contains its context (this
) and all the Number.prototype
properties, including its Symbol.toPrimitive
property. In strict mode, the context behaves a lot more nicely, allowing you to define it as a primitive value like a number instead of defaulting to window
and coercing bound primitives to Object
s.
这篇关于如何在JavaScript中构造无限fun()()()...()()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!