简体   繁体   English

使用 Function() 构造函数作为闭包

[英]Using Function() constructor as a closure

I'm trying to do something like this:我正在尝试做这样的事情:

function simpleOperations(operation) {
    let myFanction = new Function('a', 'b', 'a ' + operation + ' b');
    return myFanction
}

let sum = simpleOperations("+")
let multiplicate = simpleOperations("*")

console.log("your sum is: " + sum(3,7));
console.log("your product is: " + multiplicate(3,7));

and instead of getting:而不是得到:

your sum is: 10
your product is: 21

I'm getting this:我得到这个:

your sum is: undefined
your product is: undefined

Do you have any thoughts on how to fix it?您对如何修复它有任何想法吗? :) :)

The text body of the function needs to return the value, otherwise your a + b or a * b etc will just be an unused expression. function 的文本正文需要return值,否则您a + ba * b等将只是一个未使用的表达式。

 function simpleOperations(operation) { let myFanction = new Function('a', 'b', 'return a ' + operation + ' b'); return myFanction } let sum = simpleOperations("+") let multiplicate = simpleOperations("*") console.log("your sum is: " + sum(3,7)); console.log("your product is: " + multiplicate(3,7));

Using Function is an anti-pattern.使用Function是一种反模式。 It's one degree away from eval and there's always a better way to write things, especially considering JavaScript already supports first-class functions -它与eval相差一个度数,并且总是有更好的编写方法,尤其是考虑到 JavaScript 已经支持一流的功能-

 const add = (a, b) => a + b const multiply = (a, b) => a * b console.log("your sum is: " + add(3,7)) console.log("your product is: " + multiply(3,7))

your sum is: 10
your product is: 21

If instead you want to access functions using "+" and "*" strings, you can create a simple lookup and throw an Error when a particular operation is not supported -如果您想使用"+""*"字符串访问函数,则可以创建一个简单的查找并在不支持特定操作时抛出错误 -

 const operations = { "+": (a, b) => a + b, "*": (a, b) => a * b } function simpleOperations(op) { const f = operations[op] if (f == null) throw Error(`unsupported operation: ${op}`) return f } const add = simpleOperations("+") const multiply = simpleOperations("*") console.log("your sum is: " + add(3,7)) console.log("your product is: " + multiply(3,7)) const divide = simpleOperations("/") // <- not yet implemented

your sum is: 10
your product is: 21
Error: unsupported operation: /

Implementing a simple calculator is a great way to learn how to write your first programming language.实现一个简单的计算器是学习如何编写第一门编程语言的好方法。 If this sort of thing interests you, see this related Q&A .如果您对这类事情感兴趣,请参阅此相关问答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM