gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:22:54 25 4
gpt4 key购买 nike

我正在尝试做这样的事情:

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));

而不是得到:

your sum is: 10
your product is: 21

我明白了:

your sum is: undefined
your product is: undefined

您对如何解决它有任何想法吗? :)

最佳答案

函数的正文需要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));

关于javascript - 使用 Function() 构造函数作为闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70047664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com