Home > Back-end >  Using Function() constructor as a closure
Using Function() constructor as a closure

Time:11-21

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? :)

CodePudding user response:

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 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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Using Function is an anti-pattern. 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 -

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))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

  • Related