A function can also create with new keyword. And a function can assigning with multiple ways. And It’s called the Function Constructor. Function this is our function Constructor.
⇒ Simple Function..
// Function define & defination..
function strToObj(str){
let obj = new Object();
for (let s of str){
if (s !== ''){
obj[s] = s;
}
}
return obj;
}
// Invoking function with calling..
console.log(strToObj("Asad Anik"));
⇒ Construct a function. This mode is awesome to working and declaring function inside the Runtime😎. And the Runtime makes it the normal function as well. This also known as Runtime Function.
→ Similar function with new keyword like creating an Object or calling Class’s Constructor method.
→ Syntax ⇒ new Function(Arguments, Body);
// Actual function in JavaScript Behid the scense..
const strToObj = new Function(
'str',
`let obj = new Object();
for (let s of str){
if (s !== ''){
obj[s] = s
}
}
return obj;`
);
console.log(strToObj("Asad Anik"));
→ With multiple params.
⇒ Syntax — new Function(Argument1, Argument2, ….., Body);
// Multiple arguments..
const mySum = new Function(
'a',
'b',
`
const sum = a + b;
console.log(sum);
`
);
// Calling & Invoking..
mySum(20, 10);
→ Also can code like this way.
// Take all data of function into an object.
const fData = {
params: ['num1', 'num2'],
body: ['const sum = num1 + num2', 'return sum']
};
// Bring body array to string body..
const fBody = fData.body.reduce((acc, cur) => {
acc += cur + ';';
return acc;
}, '');
// Calling Function Constructor..
const myOwnFunc = new Function(...fData.params, fBody);
console.log(myOwnFunc(20, 10));
Multiple Operations Constructor Function.
// Mutiple Operations Constructor Function..
const Operations = [
{
args: [10, 20],
params: ['num1', 'num2'],
body: `console.log("Operation 1:", num1 + num2)`
},
{
args: [10, 20],
params: ['num1', 'num2'],
body: `console.log("Operation 2:", num1 - num2)`
},
{
args: [10, 20],
params: ['num1', 'num2'],
body: `console.log("Operation 3:", num1 * num2)`
},
{
args: [10, 20],
params: ['num1', 'num2'],
body: `console.log("Operation 4:", num1 / num2)`
},
];
// Calling Stack..
Operations.forEach((operation) => {
const fn = new Function(...operation.params, operation.body);
fn(...operation.args);
});
Top comments (0)