0

Is it okay to do the following:

// Response from an API as a string, that contains a function to call.
const stringFunc = 'myFunc({"Status":200,"Message":"This is a message"})';

function myFunc(obj) {
  console.log(obj);
}

function callBack(stringFn) {
  return Function.prototype.call(stringFn);
}

callBack(stringFunc);

Console logs:

{"Status":200,"Message":"This is a message"}

It seems to work just fine, but wanted to know if this was the correct way to go about this at all? Are there any better methods or unforeseen implications?

Thanks

2

2 Answers 2

1

Use eval method.

<!DOCTYPE html>
<html>

<body>
    <script>
        const stringFunc = 'myFunc({"Status":200,"Message":"This is a message"})';

        function myFunc(obj) {
            console.log(obj);
        }

        function callBack(stringFn) {
            return Function.prototype.call(stringFn);
        }

        eval(stringFunc);
    </script>
</body>

</html>

Sign up to request clarification or add additional context in comments.

3 Comments

Why do you still have the callback() function though? Not needed if using eval(), right?
No need of callBack if your intended to call myFunc only
Note that using eval() or using any other way to execute code from a string is a serious security issue. When the string comes from an untrusted source, an attacker can execute anything in the context of your web page. You should not do that.
1

As an alternative to eval you can use the Function constructor:

const stringFunc = 'myFunc({"Status":200,"Message":"This is a message"})';

function myFunc(obj) {
  console.log(obj);
}

const payloadFunc = new Function(stringFunc);
payloadFunc() //logs the object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.