Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

your sum is: undefined
your product is: undefined

Do you have any thoughts on how to fix it? 🙂

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading